int数组中的错误

时间:2018-05-29 03:57:39

标签: java

我是Java的新手,我想编写一个程序,它接受一个N整数和一个N整数数组作为输入。我的代码atm出错了。

    //use the following code to fetch input from console 
    Scanner reader = new Scanner(System.in);

    //Use the following code to print output
    int length = Integer.parseInt(reader.nextLine());
    int[] arr = new int[length];
    for (int counter = 0; counter < length; counter++)
    {
       arr[counter] = Integer.parseInt(reader.nextInt());
    }
    System.out.println(arr);

2 个答案:

答案 0 :(得分:2)

执行:arr[counter] = reader.nextInt(); 而不是:arr[counter] = Integer.parseInt(reader.nextInt());

答案 1 :(得分:1)

<强>修改:

  1. arr[counter] = Integer.parseInt(reader.nextInt());更改为arr[counter] = reader.nextInt();
  2. 试试这个:

    public class Main {
    
        public static void main(String[] args) {
             Scanner reader = new Scanner(System.in);
    
             //Use the following code to print output
             int length = Integer.parseInt(reader.nextLine());
             int[] arr = new int[length];
    
             for (int counter = 0; counter < length; counter++){
                 arr[counter] = reader.nextInt();
             }
    
             for(int i=0; i<arr.length; i++)
             System.out.println(arr[i]);
        }
    
    }
    

    Integer.parseInt(): - 此方法用于获取某个String的基本数据类型。

    语法: - static int parseInt(String s)

    您试图阅读int值而不是String