我无法使用for循环
初始化二维数组import java.util.Scanner;
public class Quater{
public static void main(String[] args){
//declare an array
double product[][]=new double[3][2];
//declare a Scanner object
Scanner userInput=new Scanner(System.in);
//ask the user for input
System.out.println("Please enter your data");
for(int i=0;i<=1;i++)
{
for(int j=0;j<=2;j++){
System.out.println(" enter your data");
product[i][j]=userInput.nextDouble();
}
}
}
}
问题是当我尝试输入第三个号码时,这会关闭而不能正常工作,但是,如果我将它设为双倍[100] [100],这可以工作并允许我输入6号码。
答案 0 :(得分:7)
外部循环遍历行和内部遍历列,因此您需要使用维度double[2][3]
而不是double[3][2]
的数组。
答案 1 :(得分:1)
如果您制作阵列new double[3][2]
,那么您可以访问product[i][j]
i
上升到3-1 = 2,j
上升到2-1 = 1。也就是说,索引的界限与它们在new
中出现的顺序相同。但您尝试访问product[i][j]
,其中j
为2。
答案 2 :(得分:1)
更正后的代码。看看这个。两个fors的条件是固定的。你应该使用长度来做,更好的是使用'&lt;'不是'&lt; ='。这会阻止许多人ArrayIndexOutOfBoundsException
。
public static void main(String[] args){
//declare an array
double product[][]=new double[3][2];
//declare a Scanner object
Scanner userInput=new Scanner(System.in);
//ask the user for input
System.out.println("Please enter your data");
for(int i=0;i<product.length;i++)
{
for(int j=0;j<product[i].length;j++){
System.out.println(" enter your data");
product[i][j]=userInput.nextDouble();
}
}
}
要查看效果,您只需粘贴该代码即可。
for (double[] doubles : product) {
for (double aDouble : doubles) {
System.out.println(aDouble);
}
}