Java循环数组模式 [英] Java looping array pattern
问题描述
我想知道我是否可以在以下问题上获得一些帮助。我需要创建一个以某种格式显示其输出的数组,但是我似乎无法弄清楚如何真正做到这一点。用语言很难解释这种模式,所以我附上了一张可以展示它的图像。
I was wondering if I could get some help with the following problem. I need to create an array that displays its output in a certain format, but I cannot seem to figure out how to actually get it to do so. The pattern is a little difficult to explain in words so I've attached an image that would showcase it.
下面提供的代码在下面显示输出fashion:根据用户输入的数字,假设他们输入了4,输出将是以下4x4数组:
The code provided below displays the output in the following fashion: Depending on the number the user enters, lets assume they entered 4, the output would be the following 4x4 array:
1 2 3 4
8 7 6 5
9 10 11 12
9 10 11 12
16 15 14 13
16 15 14 13
这显然不是我试图实现的模式..因此,任何帮助将不胜感激!
this clearly is not the pattern I am trying to achieve.. so any help would be appreciated!
公共类Question2 {
public class Question2 {
public static void main(String[] args) {
//declare scanner
Scanner keyboard = new Scanner (System.in);
//Prompt user to enter a digit greater than or equal to 3
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");
//read user input
int num = keyboard.nextInt();
//place constraints on int num so that if it is less than 3, the program does not execute
while(num<3 )
{
System.out.println("Lets's try this again....");
System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
num = keyboard.nextInt();
}
//2D array with number of rows and columns entered by user
int[][] array = new int [num][num];
int inc=1;
for(int i=0;i<array.length;i++)
{
if(i%2 == 0){
for(int j=0;j<array.length;j++)
{
array[i][j]=inc;
inc++;
}
}
else{
for(int j=num-1;j>=0;j--)
{
array[i][j]=inc;
inc++;
}
}
}
//display formatted output
String [][]stringConvertedTable= new String[num][num];
for(int i=0; i<num; i++) {
for(int j=0; j<num; j++) {
stringConvertedTable[i][j]= Integer.toString(array[i][j]);
System.out.print(stringConvertedTable[i][j] + "\t");
}
System.out.println("");
推荐答案
您可以通过应用$ p $
you can achieve the wrapping of the counter by applying the modulo operator with the size of the array
result[i][(k+i)%size] = counter++;
如何?
final int size = 5;
int[][] result = new int[size][size];
//the logic
int counter = 1;
for(int i = 0; i < size; i++) {
for(int k = 0; k < size; k++) {
result[i][(k+i)%size] = counter++;
}
}
//just the output
for(int i = 0; i < size; i++) {
boolean isFirst = true;
for(int k = 0; k < size; k++) {
if(isFirst)
isFirst = false;
else
System.out.print(", ");
System.out.print(result[i][k]);
}
System.out.println();
}
输出
1, 2, 3, 4, 5
10, 6, 7, 8, 9
14, 15, 11, 12, 13
18, 19, 20, 16, 17
22, 23, 24, 25, 21
这篇关于Java循环数组模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!