Java打印包含多个整数的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18041996/
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
Java printing a string containing multiple integers
提问by user2650243
Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
今天刚开始学习java,似乎无法解决这个问题。我正在关注 learnjavaonline.org 上的教程,它教你一些东西,然后要求你编写代码来做特定的事情,然后检查输出是否正确。问题是,如果它不正确,它不会说明原因,也不会为您提供正确代码的示例。
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
它希望我使用所有原语输出一个字符串,上面写着“H3110 w0r1d 2.0 true”
i came up with this
我想出了这个
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
}
but it outputs 86.0 w0r1d 2.0 true
但它输出 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
我怎样才能使它不添加所有整数,而是连续显示它们?
采纳答案by Akunosh
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
您可以使用包装类的 toString 或 valueOf 方法将您的数字转换为字符串(猜猜您还没有),或者只是将所有原语填充到没有 String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
您需要查找的只是printline 语句中有一个字符串。这意味着如果您只想打印我们可以使用的基于数字的数据类型system.out.println("" + youNumberVariable)。
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest;to force all following values into the string like it does in the printline statement.
还可以选择在输出声明的开头添加一个空字符串,output = "" + theRest;以强制所有后续值进入字符串,就像在 printline 语句中所做的那样。
Most of it is not very pretty coding but will completly suffice for the learning process.
其中大部分不是很漂亮的编码,但对于学习过程来说完全足够了。
回答by morgano
The problem with this line:
这一行的问题:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three(which evaluates to an int) and then oneand then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
是从左到右执行操作,因此它首先求和h + three(计算结果为int)one,然后是ten。到那时,您有一个数值 (an int),然后将“求和”为 a String。尝试这样的事情:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a Stringobject, evaluating the rest of the operations as Strings.
在第二种情况下,您的表达式将从一个String对象开始,将其余的操作计算为Strings。
You of course could use ""at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf()for the other operands, as the first one is already a String.
您当然可以使用""开头或任何其他计算结果为 的值String,例如String.valueOf(h). 在最后一种情况下,您不需要String.valueOf()用于其他操作数,因为第一个已经是字符串。
回答by Mena
An easy and ugly way to do this would be to use String.valueOffor each numerical value.
一个简单而丑陋的方法是使用String.valueOf每个数值。
As in:
如:
String output = h + String.valueOf(three); // + etc...
Edit
编辑
morgano's approach is perfectly valid as well - +1 for that.
摩根诺的方法也完全有效 - 为此+1。
On a more general topic, you might want to use String.concatfor Stringconcatenation, or even better, a StringBuilderobject.
在更一般的主题上,您可能希望将其String.concat用于String连接,或者甚至更好地用于StringBuilder对象。
ThisSO page contains a lot of info you can use on the matter.
此SO 页面包含许多您可以使用的信息。
回答by Mark Nenadov
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
在添加之前,我会使用 String.valueOf 将每个数值显式转换为 String。像这样:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
回答by Thorbj?rn Ravn Andersen
The trick is to get the compiler to interpret +as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to +must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
诀窍是让编译器将其解释+为字符串连接(然后默默地将数字转换为字符串),而不是将两个数字相加。这意味着 to 的两个参数之一+必须是字符串,而不是 - 作为前三个参数 - 数字(是的,字符是数字)。
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
希望数字彼此直接相邻,但在它们之间有一个空格,在野外代码中并不常见,例如:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
如果你真的不想有空格,那么就让第一个参数为空字符串:
String output = "" + h ....
You could also just change h from char to String.
您也可以将 h 从 char 更改为 String。
回答by brj
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}
回答by MahNas92
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
你得到的结果是因为,本质上,当依赖隐式转换时,你在打印数字变量之前对它们进行算术运算。
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of: 72 + 3 + 1 + 10.0 (which is equal to 86.0)
甚至 Char 也是一个数字!H 在 ascii 表中的值为 72,因此您基本上是在指示 Java 程序打印以下结果:72 + 3 + 1 + 10.0(等于 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play. In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
像这样的数字和符号混合输入的字符串连接可能会出现问题,因为隐式转换在起作用。为了确保内容符合您的要求,而不使用显式转换,可以在每个数值之间使用任一字符串,如下所示:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast tento the int-type, to lose the decimal...
请注意我需要如何ten转换为 int 类型,以丢失小数...
Above example is however not a good example of using string concatenations! For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
然而,上面的例子不是使用字符串连接的好例子!对于一个适当的解决方案,这可能更针对有更多经验的人,是尝试使用字符串格式,如下所示:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
另一种方法是使用这样的消息格式,可能不是此分配的最佳选择,因为浮点数将打印为整数。还需要导入java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));

