【问题标题】:No Console found. How to get the console for my JVM?未找到控制台。如何为我的 JVM 获取控制台?
【发布时间】:2014-06-16 03:39:33
【问题描述】:

这是this 的后续问题。

我昨天问了这个问题,虽然它还没有解决,但我尝试对代码进行一些愚蠢的更改以使其编译一次(将console.format() 语句替换为System.out.print 语句,并添加null作为readLine() 方法的第二个参数)。

幸运的是,代码确实运行了,但它打印了 No console.(显然是因为 JVM 没有控制台设备。 Reference

那么我怎样才能得到控制台设备,它应该由 Console 类的一个对象来表示呢?


为方便起见,我在对代码进行了上述愚蠢的更改以使其运行后添加代码:-

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/*
 *  Enter your regex: foo
 *  Enter input string to search: foo
 *  I found the text foo starting at index 0 and ending at index 3.
 * */

public class RegexTestHarness {

    public static void main(String[] args){
        Console console = System.console();
        if (console == null) {
            System.err.println("No console.");
            System.exit(1);
        }
        while (true) {

            Pattern pattern = 
            Pattern.compile(console.readLine("%nEnter your regex: ", null));

            Matcher matcher = 
            pattern.matcher(console.readLine("Enter input string to search: ", null));

            boolean found = false;
            while (matcher.find()) {
                /*console.format("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());*/

                System.out.println("I found the text " + matcher.group() + " starting at index " + matcher.start() + " and ending at index " + matcher.end() + "."); 

                found = true;
            }
            if(!found){
                //console.format("No match found.%n", null);
                System.out.println("No match found."); 
            }
        }
    }
}

【问题讨论】:

  • 如何运行这段代码?我感觉您正在使用 Eclipse、NetBeans 或 InteliiJ 等 IDE。
  • 是的,我正在使用 Eclipse。
  • 在这种情况下,this 你可能会感兴趣。
  • 如果您对alternative options感兴趣

标签: java regex console console-application console.readline


【解决方案1】:

如果您的应用程序是从终端启动并且没有标准输入或标准输出重定向,那么您的应用程序将只有一个控制台设备可以打开。 基本上,函数 isatty() 必须返回 true。如果 Windows 应用程序从资源管理器启动,它们通常没有控制台。您应该从命令提示符 (cmd.exe) 启动它们。

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多