我的java控制台无法正常工作
使用我的java控制台时遇到了非常严重的问题。 我已经在java程序中启用了“show console”,它位于start> control panel> programs> 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)
为了避免在运行代码时创建新的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
运行此代码,您将看到两个窗口:
但是如果使用javaw -cp pathToYourPackage Demo
你将看不到控制台窗口(这就是大多数IDE使用它的原因)但仅限于