Rather than placing an extra scanner.nextLine()
each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");
System.out.print("Enter an index: ");
int index = scanner.nextInt();
System.out.print("Enter a sentence: ");
String sentence = scanner.next();
System.out.println("\nYour sentence: " + sentence);
System.out.println("Your index: " + index);
}
}
Thus, to read a line of input, you only need scanner.next()
that has the same behavior delimiter-wise of next{Int, Double, ...}
The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also 3
, 3
and 3whatever
while the former only accepts 3
on a line on its own