我的java控制台无法运行

时间:2014-06-01 14:39:28

标签: java console

使用我的java控制台时遇到了非常严重的问题。我已经在java程序中启用了“show console”,它位于start>控制面板>程序> java。 我双击它打开,进入高级并启用显示控制台。 但是当我尝试运行此程序时,我收到错误消息没有控制台!请帮助!! 提前致谢。

    public class RegexTest {

    public static void main(String[] args) {
        // TODO code application logic here
        Console console=System.console();

        if(console==null){
            System.err.println("no console");
            System.exit(1);
        }
        while(true){
            Pattern pattern=Pattern.compile(console.readLine("enter your regex: "));
            Matcher matcher=pattern.matcher(console.readLine("enter inputstring to serch"));
            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());
                found=true;
            }
            if(!found){
                console.format("no match found %n");
            }
        }
    }
}

这是输出。

no console
Java Result: 1
BUILD SUCCESSFUL (total time: 13 seconds)

1 个答案:

答案 0 :(得分:1)

为避免在运行代码时创建新的OS控制台窗口,大多数IDE(如Eclipse,NetBeans,InteliiJ)使用javaw.exe(无窗口)而不是java.exe

由于javaw.exe没有创建控制台窗口,因此没有您想要打印的控制台,因此System.console()会返回null

这个例子可能更容易理解我的意思。

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Demo {

    public static void main(String[] args) throws Exception {

        JFrame frame = new JFrame("Hello");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.setSize(250, 100);

        frame.add(new JLabel("HELLO WORLD"));
        frame.add(new JLabel("Is console available? " + (System.console() != null)));
        frame.setVisible(true);

        System.out.println("text in console");
    }

}

如果使用java -cp pathToYourPackage Demo运行此代码,您将看到两个窗口:

enter image description here

但是如果你使用javaw -cp pathToYourPackage Demo,你将看不到控制台窗口(这就是为什么大多数IDE都使用它)但只有

enter image description here