+ 2
Problem with input in Java
I have this simple code: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num1 = input.nextInt(); String str = input.nextLine(); System.out.println(num1); System.out.println(str); } } As you can see, reads an integer and the string, and print them to the user. But I don't know why doesn't read the string, only read the int number, why?
3 Respuestas
+ 4
int num1 = Integer.parseInt(input.nextLine());
should fix your issue.
nextInt() doesn't handle the '\n' character left over from entering the number and your call to nextLine() afterwards is accepting it and the Program continues on from there.
+ 3
I understand now, thank you all!!
+ 2
Edit:
After int Num1 = input.nextInt();
You need input.nextLine(); so that the scanner is to the start of the second line before the line is read.
So:
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
input.nextLine();
String str = input.nextLine();
System.out.println(num1);
System.out.println(str);