Java System.out.println 和 String 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23772436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.out.println and String arguments
提问by
When I write:
当我写:
System.out.println("Give grade: ", args[0]);
It gives the error:
它给出了错误:
The method println(String) in the type PrintStream is not applicable for the arguments (String, String).
PrintStream 类型中的方法 println(String) 不适用于参数 (String, String)。
Why is this so? However, when I try to write
为什么会这样?但是,当我尝试写
System.out.println("Give grade :");
System.out.println(args[0]);
No error shows. Is there a way I can write the above in one line of println()
?
没有错误显示。有没有一种方法可以将上面的内容写在一行中println()
?
采纳答案by David Ehrmann
The two that work only take one parameter, the one that fails takes two. Any chance you have a Javascript or Python background? Java enforces parameter type and count (like C).
两个有效的只需要一个参数,失败的一个需要两个。你有没有 Javascript 或 Python 背景的机会?Java 强制执行参数类型和计数(如 C)。
Try
尝试
System.out.println("Give grade: " + args[0]);
System.out.println("Give grade: " + args[0]);
or
或者
System.out.printf("Give grade: %s%n", args[0]);
System.out.printf("Give grade: %s%n", args[0]);
回答by merlin2011
One line. This just does the string concatenation inline.
一条线。这只是内联字符串连接。
System.out.println("Give grade: "+ args[0]);
回答by Abimaran Kugathasan
System.out.println(String text);
internally calls PrintWriter#println()
method and it expect one argument.
System.out.println(String text);
内部调用PrintWriter#println()
方法,它需要一个参数。
You can concatenate those to String literals and passed it like below.
您可以将它们连接到字符串文字并像下面一样传递它。
System.out.println("Give grade: " + args[0]);
回答by Luiggi Mendoza
From PrintWriter#println
javadoc, it notes that it takes a single argument.
从PrintWriter#println
javadoc 中,它指出它需要一个参数。
You can, instead, concatenate the data to form a single String
parameter:
相反,您可以连接数据以形成单个String
参数:
System.out.println("Give grade: " + args[0]);
You may want to check PrintWriter#printf
:
您可能需要检查PrintWriter#printf
:
System.out.printf("Give grade: %s\n", args[0]);
Note that the method above is available since Java 5 (but surely you're using Java 7 or 8).
请注意,上述方法从 Java 5 开始就可用(但您肯定使用的是 Java 7 或 8)。
回答by Thilo
Another method that you can use is format
. It takes any number of arguments and formats them in various ways. The patterns should be familiar to you from other languages, they are pretty standard.
您可以使用的另一种方法是format
. 它接受任意数量的参数并以各种方式格式化它们。您应该熟悉其他语言的模式,它们非常标准。
System.out.format("Give grade: %s%n", args[0]);
回答by Skyline
You do can either:
你可以:
System.out.println("Give grade: " + args[0]);
or in C-like style:
或类似 C 的风格:
System.out.printf("Give grade: %s%n", args[0]);