问题
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).
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()?
回答1:
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).
Try
System.out.println("Give grade: " + args[0]);
or
System.out.printf("Give grade: %s%n", args[0]);
回答2:
One line. This just does the string concatenation inline.
System.out.println("Give grade: "+ args[0]);
回答3:
From PrintWriter#println javadoc, it notes that it takes a single argument.
You can, instead, concatenate the data to form a single String parameter:
System.out.println("Give grade: " + args[0]);
You may want to check 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).
回答4:
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.
System.out.format("Give grade: %s%n", args[0]);
回答5:
You do can either:
System.out.println("Give grade: " + args[0]);
or in C-like style:
System.out.printf("Give grade: %s%n", args[0]);
回答6:
System.out.println(String text); internally calls PrintWriter#println() method and it expect one argument.
You can concatenate those to String literals and passed it like below.
System.out.println("Give grade: " + args[0]);
来源:https://stackoverflow.com/questions/23772436/system-out-println-and-string-arguments