2016-04-24 160 views
-3

有沒有人可以幫我解決這個問題。我知道這可能是你可以用java編寫的最簡單的東西,但我無法想象它爲我的生活。我剛開始學習java,這讓我陷入困境。 當我編譯代碼它得到錯誤「INT不能轉換爲字符串console.printf(XY);int不能轉換爲字符串

import java.io.Console; 
public class ExampleProgram { 
    public static void main(String[]arg) { 
    Console console = System.console(); 
    console.printf("Below is a Power Calculation"); 
    int x = 2; 
    int y = 2; 
    int xy = x * y; 
    console.printf(xy); 
    } 
} 
+0

你不應該使用的toString()? – Ian

+0

'printf(%d,xy)' –

+0

返回錯誤:int無法取消引用 –

回答

-1

嘗試使用

console.printf(xy+""); 
+0

即使它能工作,使用連接也會失去使用'printf'的目的。 – Pshemo

3

使用printf格式說明符作爲Formatter API描述:

Console console = System.console(); 
// note that console is never guaranteed to be non-null, so check it! 
if (console == null) { 
    // error message 
    return; 
} 
console.printf("Below is a Power Calculation%n"); // %n for platform independent new-line 
int x = 2; 
int y = 2; 
int xy = x * y; 
console.printf("%d", xy); // %d for decimal display 
+0

嘿,謝謝你的工作。 –

1

有兩個部分是:

  1. 將整數轉換爲字符串可以通過多種方式完成。例如:

    xy + "" 
    

    是一種慣用的方式,它依賴於字符串連接運算符的特殊語義。

    Integer.toString(xy) 
    

    可能是最有效的。

    Integer.valueOf(xy).toString() 
    

    轉換xyInteger,然後應用toString()實例方法。

    但這行不通

    xy.toString() 
    

    ,因爲1)你不能一個方法適用於原始,和2)Java將不autobox xy在這方面的Integer

  2. 要打印的字符串的方法是「一種錯誤」。 printf方法的簽名是printf(String format, Object... args)。當您按照自己的方式進行調用時,您將format和零長度args參數一起傳遞給該參數。

    printf方法將解析format尋找表示替換標記的%字符。幸運的是,一個數字字符串不包含這些字符,所以它將被逐字打印。

    但無論如何,「正確」的方式來使用printf的是:

    printf("%d", xy) 
    

    依賴於printf做數字符串轉換。

還有另一個潛在的問題。如果您在「無頭」系統上運行此程序,System.console()方法可能會返回null。如果發生這種情況,您的程序將與NPE一起崩潰。


1 - 用一個簡單的測試用例上的Java證實8

0

用途: console.printf(String.valueOf(xy));