public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=scan.nextInt();
// double d=scan.nextDouble();
// Write your code here.
Double d = 0.0;
try {
d = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String s=scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
Asked
Active
Viewed 66 times
-6
![](../../users/profiles/1336174.webp)
Douwe de Haan
- 5,038
- 1
- 24
- 37
![](../../users/profiles/6592688.webp)
Aditya
- 3
- 3
-
1It would be great if you [format your code first](https://stackoverflow.com/posts/44539167/edit) – ΦXocę 웃 Пepeúpa ツ Jun 14 '17 at 08:16
-
I'm new .Don't know how to format code.Sorry – Aditya Jun 14 '17 at 08:18
-
2And say what happened vs what you expected to happen. – Jon Skeet Jun 14 '17 at 08:18
-
See https://stackoverflow.com/editing-help – Jon Skeet Jun 14 '17 at 08:18
-
We cannot effectively help you until you provide a [MCVE / SSCCE](http://sscce.org/)code and accurately describe the problem i.e. what do you give/expect for input/output. – ΦXocę 웃 Пepeúpa ツ Jun 14 '17 at 08:19
-
the input which I've given for String and double isn't coming as output – Aditya Jun 14 '17 at 08:25
-
Dupe: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – Tom Jun 14 '17 at 08:30
2 Answers
0
Your code can be changed to the following (remember that it's always a good idea to close the scanner):
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int i = scan.nextInt();
double d = scan.nextDouble();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
scan.close();
}
![](../../users/profiles/6377012.webp)
Christian
- 56
- 5
0
It's because when you enter a number and press Enter key, scan.nextInt()
consumes only the entered number, not the "end of line". When scan.nextLine()
executes, it consumes the "end of line" still in the buffer from the first input which you have provided during the execution of scan.nextInt()
.
Instead, use scan.nextLine()
immediately after scan.nextInt()
.
in your current scenario you will get the exception,
java.lang.NumberFormatException: empty String
Your modified code will be as,
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
scan.nextLine();
// double d=scan.nextDouble();
// Write your code here.
Double d = 0.0;
try {
d = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
![](../../users/profiles/5577819.webp)
Zia
- 1,080
- 10
- 23