0

I have the following input in 3 lines:

line 1: consists of positive int m and n separated by white space

line 2: list of m int separated by white space

line 3 and beyond: list of n words separated by white space or newline character

I am unable to read beyond m and n into my code

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

Java Coder
  • 119
  • 11
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Johannes Kuhn Nov 01 '19 at 05:31
  • it did not already tried it. my input comes in three or more lines. i can read m and n fine, but not sure how to move to the second line and use my for loop to read the integers and then how to move it to the third line and read all the strings – Java Coder Nov 01 '19 at 05:33
  • How does your code even compile? It's not `nextline()` but `nextLine()`. At which line do you get the null pointer exception? – John Red Nov 01 '19 at 05:58
  • inside the first for loop – Java Coder Nov 01 '19 at 06:02

2 Answers2

1

I think below is what you are looking for. Made small changes to your program. You don't really need 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();
}

www.hybriscx.com
  • 1,091
  • 2
  • 21
0

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]
Brian
  • 21
  • 2