首页 > 解决方案 > 扩展 Java 数组时遇到问题

问题描述

我目前正在用 Java 编写一个数组,该数组要求用户输入一个数字,该数字会导致扩展数组,而无需使用 if...else 或 switch 之类的条件循环。例如:如果用户输入 2:输出:2 2 2 2 1 2 2 2 2

或者如果用户输入 3:输出:3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3

这是我到目前为止所得到的,但它违反了无条件 if...else 的规则。

import java.util.*;

public class Test2 
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        
        int choice;
        String space= " ";
        System.out.println("Please Enter an input : ");
        choice=input.nextInt();
        int adapt[];
        int num=choice;
        int increment=choice-1;
        
        
        if(choice==2)
        {
            for(int i=0; i<=choice; i++)
            {
                for(int j=0; j<choice-increment; j++)
                {
                    System.out.print(space + (choice) + space);
                }

                for(int j=choice-increment; j<choice; j++)
                {
                    if(i==choice-increment) 
                    {
                        System.out.print(space + (choice-increment) + space);
                    }
                    else
                    System.out.print(space + (choice) + space);
                }

                for(int j=choice-increment; j<choice; j++)
                {
                    System.out.print(space + (choice) + space);
                }
                System.out.println();
            }
        }            
    }
}
        

标签: javaarrays

解决方案


问题的措辞令人困惑。检查您的代码,您似乎正在尝试绘制一个整数方形网格,其中数字从网格中间的中心数字 (1) 径向递增。这是一个典型的编程问题,旨在教你循环和索引。因此,您的问题实际上与 Java 无关,但是我在下面为您提供了一个可用的 Java 解决方案。

条件语句不是解决此问题所必需的。唯一需要的语言结构是 for 循环,特别是双嵌套 for 循环,因为这是一个二维问题。

public class Grid {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please Enter an input : ");
    final int p = input.nextInt();
    // square grid with side length 2p + 1
    final int[][] grid = initGrid(2 * p + 1);
    fillGrid(grid, p);
    printGrid(grid);
  }

  private static int[][] initGrid(int size) {
    // 2-d int array
    int[][] grid = new int[size][];
    for (int i = 0; i < size; i++) {
      grid[i] = new int[size];
    }
    return grid;
  }

  private static void fillGrid(int[][] grid, int p) {
    for (int row = 0; row < grid.length; row++) {
      for (int col = 0; col < grid[row].length; col++) {
        grid[row][col] = calculateValue(row, col, p);
      }
    }
  }

  private static int calculateValue(int row, int col, int centre) {
    // the algorithm for calculating the value of the cell
    int dx = Math.abs(row - centre);
    int dy = Math.abs(col - centre);
    return 1 + Math.max(dx, dy);
  }

  private static void printGrid(int[][] grid) {
    for (final int[] row : grid) {
      for (int cell : row) {
        System.out.print(String.format(" %2d ", cell));
      }
      System.out.println();
    }
  }
}

推荐阅读