Java打印包含多个整数的字符串

use*_*243 3 java string integer output

刚刚开始学习java,似乎无法弄清楚这一点.我正在学习learnjavaonline.org上的教程,它教你一些事情,然后要求你编写一个代码来做一个特定的事情,然后检查输出以查看它是否正确.问题是,如果它不正确,它没有说明原因,或者给你一个正确代码的例子.

它希望我使用所有基元输出一个字符串"H3110 w0r1d 2.0 true"

我想出了这个

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);
}
Run Code Online (Sandbox Code Playgroud)

}

但它输出 86.0 w0r1d 2.0 true

我怎么能这样做它不添加所有整数,但连续显示它们?

mor*_*ano 5

这条线的问题:

String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
Run Code Online (Sandbox Code Playgroud)

是操作是从左到右执行的,所以它首先求和h + three(对其求值int)然后one再求和ten.到那时为止,你有一个数值(a int),然后将它"加"到a String.尝试这样的事情:

String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,表达式将以String对象开头,将其余操作评估为Strings.

你当然可以""在开头使用或任何其他评估的值String,比如String.valueOf(h).在最后一种情况下,您不需要使用String.valueOf()其他操作数,因为第一个操作数已经是String.


Aku*_*osh 2

您可以使用包装类的 toString 或 valueOf 方法将数字转换为字符串(猜猜您还没有实现),或者只是将所有原语填充到打印行中,而无需 String output.

system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
Run Code Online (Sandbox Code Playgroud)

您需要查找的只是 printline 语句中有一个字符串。这意味着如果您只想打印我们基于数字的数据类型,您可以使用system.out.println("" + youNumberVariable).

还可以选择在输出声明的开头添加一个空字符串,output = "" + theRest;以将所有后续值强制放入字符串中,就像在 printline 语句中一样。

其中大部分不是非常漂亮的编码,但对于学习过程来说完全足够了。