java - 强制Java使用用户输入作为消息进行编译错误

标签 java compiler-errors

我不知道在Java中是否可行;我想从用户(从System.in)获得输入,然后使用该输入引发编译错误。我的意思是,如果用户输入了文本“HELLO”,则程序应引发编译错误:编译错误:HELLO。我想要一个错误,该错误实际上使程序在该点处停止执行该消息。

这可能吗?如果是,如何?

实际上,我想在运行时犯一个编译错误!

代码将如下所示:

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
String str = in.nextLine();

//compileError(str); this part must be completed


    }
}

这可能吗?

最佳答案

您可以在此时停止程序执行。例如:

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        if (str.equals("HELLO")) {
            System.out.println("Compile Error: " + str);
            System.exit(1);
        }
        // Do something else.
    }
}

另一种方法是引发异常...,除了您将获得异常堆栈跟踪以及一条消息。在您执行此操作的上下文中,这可能并不重要。

请注意,这存在一些潜在的问题:
  • 如果法官拦截了所有输出,则可能无法掌握应用程序生成的消息。
  • 法官在每次对其进行判断时,可能会向您的应用程序提供不同的输入。


  • 但是,这不是真正的编译错误。的确,对于您的程序来说,生成真正的编译错误并不意味着

    编译错误发生在编译代码时,它们由编译器输出。但是Java应用程序无法在编译时读取输入(来自用户或“法官”)。它可以在运行时读取输入...但是对于编译错误来说为时已晚。

    您似乎对术语感到困惑。我建议您阅读这些文章,以了解各种术语的含义:
  • 编译错误或编译器错误-https://en.wikipedia.org/wiki/Compilation_error
  • 运行时错误-https://techterms.com/definition/runtime_error
  • 异常-https://techterms.com/definition/exception


  • 您对此发表了评论:

    Think that you are given a program that you don't know what it should do and it pass some tests on an online judge. You know what the input could be but don't know in which order they come and you should get the test cases without actually accessing the online judge's test cases. I want to make my program give me some errors to find out what is in each test case.





    I just have a working program and want to extract the input from online judge.



    那不是您在谈论的编译错误。那是一个运行时错误,因为您希望/需要在程序运行时发生它。请引用上面的链接以获取这些术语的解释。

    关于java - 强制Java使用用户输入作为消息进行编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55323763/

    相关文章:

    c - 如何使用 OpenSSL 编译 .c 文件包括?

    c++ - 编译 Google Test 时出现 g++ fatal error

    c++ - 如果调用某些函数,我可以强制编译器错误吗?

    java - 使用 UTF-8 资源本地化 JSF 1.2 应用程序

    Java:不同参数顺序的测试方法

    java - Android Studio 无法从 'generated_java' 文件夹导入 java

    java - 使用单独的类加载器运行每个 JUnit 测试(不,真的)

    java - 使用正则表达式屏蔽字符串的一部分

    c# - 如何修复下面的LinQ笛卡尔程序并使之运行?

    c++ - C++错误,编译器无法识别字符串::push_back [closed]