A
A
Alexey Mazurkevich2020-12-29 23:08:51
Java
Alexey Mazurkevich, 2020-12-29 23:08:51

Why does java throw an error when I use Scanner?

I wrote the most lightweight program so as not to litter the question:

package ****;
import java.util.Scanner;
public class Main {

 public static void main(String[] args) {
     Scanner sc = new Scanner (System.in);
     System.out.println("Enter your name: ");
     String name = sc.nextLine();
     System.out.println("Enter your age: ");
     int age = sc.nextInt();
   }
}

Error:
Task :run FAILED
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Expirement.Main.main(Main.java:7)

FAILURE : Build failed with an exception.

* What went wrong:
Execution failed for task ':run'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_271\bin\java.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
2 actionable tasks: 2 executed

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor Makhov, 2020-12-29
@Igorgro

https://stackoverflow.com/a/7209487/6912339

W
Wataru, 2020-12-30
@wataru

Aleksey Mazurkevich , please place the code in the code tag ("< / >" button in the editor). Make good indents. Otherwise, almost no one will read your code at all.
Error messages are also better wrapped in code.

B
BorLaze, 2020-12-30
@BorLaze

And what is this mysterious way to first read the answer, and then display a hint on the screen? :-)

String name = sc.nextLine();
System.out.println("Enter your name: ");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question