gpt4 book ai didi

java - 二维阵列打印在一列错误

转载 作者:行者123 更新时间:2023-12-01 22:59:17 25 4
gpt4 key购买 nike

请记住我的 switch 语句尚未完成。我试图弄清楚为什么当我尝试打印 intArray 时,所有内容都出现在单个列中。如果有人需要详细信息,请随时询问。

    import java.util.*;
public class twoDimensionalArray
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int choice, row, col, upper, lower;
System.out.println("Choose the number of rows for the array");
row = console.nextInt();
System.out.println("Choose the number of columns for the array");
col = console.nextInt();
int[][] intArray = new int[row][col];
choice = Menu();
switch(choice)
{
case 1:
do
{
System.out.println("Choose a lower bound for the random numbers");
lower = console.nextInt();
System.out.println("Choose an upper bound for the random numbers");
upper = console.nextInt();
if (lower > upper)
{
System.out.println("The lower bound must be less than the upper bound");
}
}
while (lower > upper);
fillArray(intArray, upper, lower);
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: System.exit(0);
}
}
public static int Menu()
{
Scanner console = new Scanner(System.in);
int choice;
do
{
System.out.println("Enter the number corresponding to your choice:\n"
+ "1) Fill the array with new values \n"
+ "2) Find largest element \n"
+ "3) Find smallest element \n"
+ "4) Find Sum of elements \n"
+ "5) Find average of elements \n"
+ "6) Count the number of even elements \n"
+ "7) Total the odd values \n"
+ "8) FindIt \n"
+ "9) Print Array \n"
+ "10) Exit");
choice = console.nextInt();
}
while (choice < 1 || choice > 10);
return choice;
}
public static int[][] fillArray(int[][] intArray, int upper, int lower)
{
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
intArray[row][col] = lower + (int)(Math.random() * ((upper - lower) + 1));
}
}
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}
return intArray;
}//end fillArray
}//end program

最佳答案

System.out.println() 和 System.out.print() 之间存在差异。

您的代码:

for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}

我的代码:

for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.print(intArray[row][col]);
}
System.out.println("");
}

print() 打印字符串参数,而 println() 打印参数后跟一个新行。我还在行之间添加了对 println() 的额外调用,以便它们在自己的行上打印出来。

关于java - 二维阵列打印在一列错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com