2013-10-18 47 views
1

我是初學者。只是想知道爲什麼這個代碼在窗戶完全正常的命令提示符下,但我得到的:在eclipseEclipse中的NullPointerException但不是命令Promt

Exception in thread "main" java.lang.NullPointerException 
    at Test1.main(Test1.java:13) 

錯誤。這對我來說發生了很多事情,並且它實際上阻止了我使用eclipse。

這裏是代碼:

import java.io.Console;

public class Test1 { 

    public static void main(String[] args) {   
     Console myConsole = System.console(); 

     for (int a = 0; a < 10; a++){   
      int a2 = a * a;   
      myConsole.printf("\n%d squared is: %d.",a,a2); //Problem with this line 
     }  
     System.exit(0); 
    } 
} 

回答

3

簡單地說,System.console()在Eclipse中返回null,但在控制檯中運行時不會。這是documented行爲:

返回與當前Java虛擬機關聯的唯一控制檯對象(如果有)。

返回:
系統控制檯(如果有)否則爲空。

爲什麼不直接用System.out代替?畢竟,你不需要需要Console的任何功能。

2

System#console可能在某些環境下返回null。既然你只是輸出到控制檯,你不需要使用ConsoleFormatter可以用來代替:

System.out.printf("\n%d squared is: %d.", a, a2); 
4

的Javadoc System.console()狀態

返回系統控制檯,如果有的話,否則返回null。

Eclipse不能關聯繫統控制檯。

改爲使用System.in代替,可能使用java.util.Scanner作爲輸入。輸出爲System.out

+0

當OP僅將控制檯用於* output *時,System.in究竟有多有用? –

+0

@JonSkeet編輯了這一點。 –

相關問題