简体   繁体   English

Java扫描仪输入读数

[英]Java scanner input reading

I have the following input in 3 lines:我在 3 行中有以下输入:

line 1: consists of positive int m and n separated by white space第 1 行:由正整数 m 和 n 组成,由空格分隔

line 2: list of m int separated by white space第 2 行:由空格分隔的 m int 列表

line 3 and beyond: list of n words separated by white space or newline character第 3 行及以后:由空格或换行符分隔的 n 个单词的列表

I am unable to read beyond m and n into my code我无法将 m 和 n 读入我的代码

My Code:我的代码:

Scanner input = new Scanner(System.in);
m = input.nextInt();
n = input.nextInt();
int[] lines = new int[m];
String[] words = new String[n];
input.nextLine();
for (int i = 0; i < m; i++) {
    lines[i] = input.nextInt();
}
for (int i = 0; i < n; i++) {
    words[i] = input.next();
}

How to read the line and words into the arrays after i call the first nextLine(), and try to read the numbers, i get a nullpointerexception如何在我调用第一个 nextLine() 后将行和单词读入 arrays,并尝试读取数字,我得到一个空指针异常

I think below is what you are looking for.我认为下面是您正在寻找的。 Made small changes to your program.对您的程序进行了一些小改动。 You don't really need line input.nextLine() .你真的不需要 line input.nextLine() Hope it helps希望能帮助到你

Example Input示例输入

3 2
9 5 2
Good Luck

PROGRAM程序

Scanner input = new Scanner(System.in);

int m = input.nextInt();
int n= input.nextInt();

int[] lines = new int[m];
for (int i = 0; i < m; i++) {
    lines[i] = input.nextInt();
}

String[] words = new String[n];
for (int i = 0; i < n; i++) {
    words[i] = input.next();
}

I had the user insert the input one line at at time here.我让用户在这里一次插入一行输入。 I'm not sure what you were looking for but this is what I have:我不确定你在找什么,但这就是我所拥有的:

Program:程序:

Scanner input = new Scanner(System.in);
System.out.print("Enter line 1: ");
int m = input.nextInt();
int n = input.nextInt();
System.out.println(m + " ints and " + n + " words");
System.out.print("Enter line 2: ");
int[] lines = new int[m];
String[] words = new String[n];
input.nextLine();
for (int i = 0; i < m; i++) {
    lines[i] = input.nextInt();
}
System.out.print("Enter line 3: ");
for (int i = 0; i < n; i++) {
    words[i] = input.next();
}
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(words));

Console:安慰:

Enter line 1: 3 4
3 ints and 4 words
Enter line 2: 1 2 3
Enter line 3: four words right here
[1, 2, 3]
[four, words, right, here]

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

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