简体   繁体   English

如何在 JAVA 中使用二维数组从用户那里获取多个输入?

[英]How to take multiple inputs from he user using 2D array in JAVA?

While completing a problem i got a problem where i am getting run time error whenever user giving more than 3 inputs .在完成一个问题时,我遇到了一个问题,当用户提供超过 3 个输入时,我会收到运行时错误。 Example of 5 inputs line given bellow下面给出的 5 个输入线的示例

Input:输入:

2 5 2 5

5 1 5 1

2 1 2 1

3 1 3 1

1 1 1 1

4 1 4 1

In the first line "5" is number of test cases .第一行“5”是测试用例的数量。

My code only runs for first 3 lines of inputs i hope anyone can help me to identify the problem in my code so that it works for any number of input line given by the user .我的代码只针对前 3 行输入运行,我希望任何人都可以帮助我识别代码中的问题,以便它适用于用户提供的任意数量的输入行。

import java.util.Scanner;

public class Test{

public static void main(String[]args){

    Scanner robo=new Scanner(System.in);
    int num=robo.nextInt();
    int array [][]=new int [5][2];

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

    int word=num;
    String result="";

    if(array[0][0]>num){
      System.out.print("NO");
    }else{
      for(int i=0;i<num1-1;i++){       
        word=array[i][1]+word;
        if(array[i+1][0]<word){
          result="YES";
        }else{
          result="NO";
        }
      }
      System.out.println(result);
    }
  }
}

I think I see your problem:我想我看到了你的问题:

In this loop:在这个循环中:

for(int i=0;i<array.length;i++){

  for(int j=0;j<array.length;j++){

    array[i][j]=robo.nextInt();
  }

}

i runs from 0 to 4 and j ALSO runs from 0 to 4, because the length of your array is 5, even if each of the 5 array entries is an array with size 2. Still array.length of the "outer" array is 5. And therefore array[i][j] will throw an exception as soon as j becomes 2 or bigger, because each of the inner arrays has only 2 elements. i从0至4和j也运行从0到4,因为你的阵列的长度是5,即使在各5个阵列条目是具有大小2的阵列仍array.length “外部”阵列是5. 因此,只要j变为 2 或更大, array[i][j]就会抛出异常,因为每个内部数组只有 2 个元素。

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

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