I've been trying to write a simple application using Scanner in Java and was having issues. I would constantly get the NoSuchElementException thrown by the scanner no matter what.
Here is my full error, code, and my build.gradle.kts :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at App.main(App.java:11)
CODE:
public class App {
public static void main(String[] args) {
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// takes input from the keyboard
String name = input.nextLine();
// prints the name
System.out.println("My name is " + name);
}
}
BUILD.GRADLE.KTS :
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.2.1/userguide/building_java_projects.html in the Gradle documentation.
*/
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
// This dependency is used by the application.
implementation("com.google.guava:guava:31.1-jre")
}
// Apply a specific Java toolchain to ease working on different environments.
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
application {
// Define the main class for the application.
mainClass.set("project.App")
}
tasks.named<Test>("test") {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
plugins {
application
}
tasks.named<JavaExec>("run") {
standardInput = System.`in`
}
I changed my code a few time, tried with Buffered Reader, but I couldn't get input. I expected it would be a problem with my code, but since I'm new to Gradle, I started exploring the possibility that it's an issue with the way I set up Gradle. I found this thread and tried copy and pasting the kotlin code that other people said worked for them. Looking through the docs, it seems to be correct. Even with this new code snippet (at the bottom of the build.gradle.kts file), I still get NoSuchElementExceptions and cannot get user input. I am running my project with the gradle extension in vscode, but I get the same issue running it in the command prompt (gradle run) on the windows command line.