2016-04-24 138 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));