【问题标题】:Same Java code Failed to run under Java Gradle Application相同的 Java 代码无法在 Java Gradle 应用程序下运行
【发布时间】:2021-01-22 04:38:02
【问题描述】:

我在 Netbeans Gradle Java 应用程序下运行以下代码时遇到了一个问题。

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class Main {
    private static int imgBundle;
    private static int flacBundle;
    private static int vidBundle;
    public static void main(String[] args) {
        takeInput();
    }
    private static void takeInput() {
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the number of Image format for the order: ");
        imgBundle = input.nextInt();     // where the error occurred
        System.out.print("Please enter the number of Audio format for the order: ");
        flacBundle = input.nextInt();    // where the error occurred
        System.out.print("Please enter the number of Video format for the order: ");
        vidBundle = input.nextInt();     // where the error occurred
        System.out.println("Your Order Input:");
        System.out.println(imgBundle + " IMG");
        System.out.println(flacBundle + " FLAC");
        System.out.println(vidBundle + " VID");
        System.out.println("");
        System.out.println("Calculating...Please wait...");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
}

发生错误

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at BundlesCalculator.Main.takeInput(Main.java:65)
    at BundlesCalculator.Main.main(Main.java:43)

但是,我在没有 Gradle 的简单 Java 应用程序中编写了相同的代码,没有出现问题。 我只是想知道我做错了什么?

【问题讨论】:

    标签: java gradle netbeans nosuchelementexception


    【解决方案1】:

    Scanner 如果没有更多输入要读取,将抛出该异常。如果您的输入文件为空,或者它不包含所有 nextInt() 调用的足够数据,则可能会发生这种情况。

    如果输入来自终端,您在读取所有输入之前提供了文件结尾(Windows 上的 Ctrl-Z,Linux 上的 Ctrl-D)。

    【讨论】:

    • 我该如何解决这个问题?我尝试使用 if (input.hasNextInt()),但该方法不接受来自终端的输入。它只是打印了我在 else 语句中设置的错误消息
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多