请记住我的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
答案 0 :(得分:2)
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()
打印String参数,而println()
打印参数后跟一个新行。我还在行之间添加了对println()
的额外调用,以便它们可以在各自的行上打印出来。
答案 1 :(得分:1)
System.out.println(intArray [row] [col]) - println将以新行结束每个打印。要避免这种情况,请使用system.out.print()