我有一个类的以下代码:
public class sqrt
{
public sqrt()
{
char start = 'H';
int second = 3110;
char third = 'w';
byte fourth = 0;
char fifth = 'r';
int sixth = 1;
char seventh = 'd';
float eighth = 2.0f;
boolean ninth = true;
String output = new String(start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
System.out.println(output);
}
}
所需的输出是:
H3110 w0r1d 2.0 true
但是,这会输出以下内容:
3182 w0r1d 2.0 true
我只能假设这是因为它看到了 char 'H'
的数字 (ASCII) 值并将其添加到 int 3110
。
我的问题是:
不应该 new String()
将其中的每个项目转换为字符串并将它们连接起来吗?
如果我将输出更改为:
String output = start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth +
" " + ninth;
它执行相同的操作,并将 char
和 int
的值相加,然后再连接其余部分。
我知道我可以通过在 start
之前添加 ""+
来克服这个问题,我想这解释了为什么它会看到 char ' 的 ASCII 值H'
(因为它查看下一个值,发现它是一个 int,然后从那里开始?),但我很困惑为什么 new String()
不是按预期工作。
PS,我想写出更好的问题,而且我知道我在这里仍然有点初学者,所以在这方面的任何建议也将不胜感激。如果有人愿意花时间提供帮助,我们非常欢迎 PM。
PPS,如果我弄清楚这是为什么,我会自己发布答案,但我真的很想学习这个,而且我只是很困惑。
最佳答案
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int
3110
.
这是完全正确的。
Shouldn't
new String()
convert each item within to a string and concatenate them?
String
构造函数对此无法控制,因为表达式 start + secondary + ""+ ...
之前已计算过。
这里的简洁方法是使用 StringBuilder
。它具有接受所有原始类型和任意对象的方法。
String output = new StringBuilder().append(start).append(second).append(' ')
.append(third).append(fourth).append(fifth).append(sixth).appends(seventh)
.append(' ').append(eighth).append(' ').append(ninth).toString();
或
StringBuilder builder = new StringBuilder();
builder.append(first);
builder.append(second);
builder.append(' ');
builder.append(third);
builder.append(fourth);
builder.append(firth);
builder.append(sixth);
builder.append(seventh);
builder.append(' ');
builder.append(eighth);
builder.append(ninth);
String output = builder.toString();
关于java - String n = new String( char + int) 添加但应该连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491808/