2014-06-16 115 views
0

這是this的後續問題。未找到控制檯。如何讓我的JVM的控制檯?

我昨天問過這個問題,雖然它尚未解決,我試圖對代碼做一些愚蠢的變化,只是讓它一次編譯(由System.out.print語句替換console.format()報表,並添加null作爲第二個參數到readLine()方法)。

幸運的是,代碼並運行,但它打印No console.(顯然是因爲JVM沒有一個控制檯設備。Reference

所以,我怎麼能得到控制檯設備,應該是代表由控制檯類的對象?


爲了方便起見,我加入的代碼後,我做給它的上述愚蠢的變化,使其運行: -

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."); 
      } 
     } 
    } 
} 
+0

你如何運行此代碼?我有一種感覺,你正在使用Eclipse,NetBeans或InteliiJ等IDE。 – Pshemo

+0

是的,我使用Eclipse。 – Solace

+1

在這種情況下[this](http://stackoverflow.com/a/23981357/1393766)可能會讓你感興趣。 – Pshemo

回答

0

您的應用程序只會有一個控制檯設備打開如果它是從終端啓動的,並且沒有標準輸入或標準輸出重定向。 基本上函數isatty()將不得不返回true。如果Windows應用程序是從資源管理器啓動的,則它們通常沒有控制檯。您應該從命令提示符(cmd.exe)啓動它們。