You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle Kotlin 8.2中Scanner无法等待输入报错的解决办法

Gradle Kotlin 8.2中Scanner读取输入抛出NoSuchElementException的解决办法

在使用Gradle Kotlin 8.2运行Java项目时,程序未等待*Scanner*读取用户输入就抛出异常:

Exception in thread "main" java.util.NoSuchElementException: No line found

主类代码

Scanner scanner = new Scanner(System.in);

System.out.println("What would you like to do?\n==========================\n0) Quit\n1) Show all class1\n2) Show specific class1\n3)Show all class2\n4)Show specific class2");
System.out.print("Choice (0-4): ");
String choice = scanner.nextLine();

System.out.println("You chose " + choice);

初始build.gradle.kts配置

plugins {
    id("java")
    id("application")
}

application {
    mainClass.set("program.StartApplication")
}

group = ".program"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.9.1"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    implementation("com.google.code.gson:gson:2.10.1")
}

tasks.test {
    useJUnitPlatform()
}

无效尝试

曾尝试添加以下配置,但未解决问题:

tasks {
    run {
        System.`in`
    }
}

有效解决方案

在build.gradle.kts中添加以下配置,将run任务的标准输入绑定到系统输入流:

tasks.getByName("run", JavaExec::class) {
    standardInput = System.`in`
}

内容的提问来源于stack exchange,提问作者Roman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:10:18