简体   繁体   中英

User input numbers into a 2 dimensional array in java

I'm having trouble with user input in java, hope anyone can help :) The user declares how big the 2d array will be(number d is the side of the square array), then inputs a number "n", which tells the program how many inputs of numbers there will be, and then needs to input these numbers (eg. if n=4, the input must be sth like : 5 17 3 20. I have already written the same thing for a single row array

for(i=0;i<=n;i++) {
    arr[i]=sc.nextInt();
}

but am having trouble doing basically the same for the 2d array. Any ideas?

使用两个嵌套循环和类似arr[i][j]索引

Sorry I don't have the ability to comment yet so I am posting this as an answer. Essentially you need to use a nested for loop as stated above. I will provide you a basic template

for (int i = 0; i < length; i ++){
  for (int j = 0; j < width; j ++){
    if (counter < userInput){
    counter++;
    arr[i][j] = value;
      } else {
        break;        
      }
  }
}
            int d=sc.nextInt(); //length of rows and columns
            int n=sc.nextInt(); //user input how many  numbers



            int[][] array=new int[d][d]; //length and heigth of array

            for (int i=0;i<d;i++) {
                    for(int j=0;j<d;j++) {
                        array[i][j]=sc.nextInt();
                    }
            }   



            int distance=0;
            int c=0;
                for(int i=0;i<d;i++){
                    for(int j=0;j<d;j++){
                        array[i][j]=c;
                        c++;




                    }

                }

that in the end is sth else, I just wanted for the whole thing to be seen, if maybe I missed something elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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