简体   繁体   English

无法使用for循环在java中初始化二维数组

[英]can not initialize a two dimensional array in java using for loop

I can not initialize a two dimensional array using for loop 我无法使用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();
        } 
      }
    }
  }

The problem is when I try to enter the third number, This shut down and not working, however, if I make it new double[100][100], this can work and allow me to enter 6 number. 问题是当我尝试输入第三个数字时,这会关闭而不能正常工作,但是,如果我将它设为新的双[100] [100],这可以工作并允许我输入6个数字。

外循环遍历行和内部遍历列,因此您需要具有double[2][3]精度数组double[2][3] ,而不是您使用的double[3][2]

If you make your array new double[3][2] , then you can access product[i][j] where i goes up to 3-1=2, and j goes up to 2-1=1. 如果你使你的阵列成为new double[3][2] ,那么你可以访问product[i][j] ,其中i上升到3-1 = 2, j上升到2-1 = 1。 That is, the bounds of the indexes in the same order in which they appear in the new . 也就是说,索引的界限与它们在new出现的顺序相同。 But you're trying to access product[i][j] where j is 2. 但是你正试图访问product[i][j] ,其中j是2。

Corrected code. 更正了代码。 Look on this. 看看这个。 Condition of two fors was fixed. 两个fors的条件是固定的。 You should do it using length and better is using '<' not '<='. 你应该使用长度来做,更好的是使用'<'not'<='。 That prevent you from many ArrayIndexOutOfBoundsException . 这会阻止您从许多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();

                }
            }
        }

to see the efect you can simply paste down that code. 要查看效果,您只需粘贴该代码即可。

for (double[] doubles : product) {
                for (double aDouble : doubles) {
                    System.out.println(aDouble);
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM