System.out.println和String参数

时间:2014-05-21 01:11:58

标签: java println

当我写:

System.out.println("Give grade: ", args[0]);

它给出错误:

  

PrintStream类型中的println(String)方法不适用于参数(String,String)。

为什么会这样?但是,当我尝试写

System.out.println("Give grade :");
System.out.println(args[0]);

没有错误显示。有没有办法可以在println()的一行中编写上述内容?

6 个答案:

答案 0 :(得分:5)

两个只能使用一个参数,一个失败的参数需要两个参数。你有机会获得Javascript或Python背景吗? Java强制执行参数类型和计数(如C)。

尝试

System.out.println("Give grade: " + args[0]);

System.out.printf("Give grade: %s%n", args[0]);

答案 1 :(得分:1)

一行。这只是字符串连接内联。

System.out.println("Give grade: "+ args[0]);

答案 2 :(得分:1)

来自PrintWriter#println javadoc,它指出它需要一个参数。

您可以将数据连接起来形成一个String参数:

System.out.println("Give grade: " + args[0]);

您可以查看PrintWriter#printf

System.out.printf("Give grade: %s\n", args[0]);

请注意,自Java 5以来,上述方法可用(但肯定是使用Java 7或8)。

答案 3 :(得分:1)

您可以使用的另一种方法是format。它需要任意数量的参数并以各种方式格式化它们。您应该从其他语言中熟悉这些模式,它们非常标准。

System.out.format("Give grade: %s%n", args[0]);

答案 4 :(得分:1)

您可以:

System.out.println("Give grade: " + args[0]);

或类似C的风格:

System.out.printf("Give grade: %s%n", args[0]);

答案 5 :(得分:0)

System.out.println(String text);内部调用PrintWriter#println()方法,它期望一个参数。

您可以将它们连接到String文字并传递它,如下所示。

System.out.println("Give grade: " + args[0]);