java - String n = new String( char + int) 添加但应该连接

标签 java string concatenation

我有一个类的以下代码:

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;

它执行相同的操作,并将 charint 的值相加,然后再连接其余部分。

我知道我可以通过在 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/

相关文章:

java - 从 persistence.xml 注入(inject) PersistenceContext

c - C语言如何通过索引从字符串中获取字符?

c++ - 计算子字符串实例数的简单 C++ 程序

string - 带有空检查的 Groovy 字符串连接

php - 如何使用此代码连接 sql、html 和 php

用于创建文件的 Matlab 字符串连接

java - 如何使用 GridView 打开 Activity 。安卓

java - 如何返回仅包含短页面信息的分页代码?

java在eclipse中运行但不会在命令提示符下运行

c# - 截断字符串时意外拆分 unicode 字符