Java打印包含多个整数的字符串 [英] Java printing a string containing multiple integers

查看:358
本文介绍了Java打印包含多个整数的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

它要我输出一个字符串说 H3110 w0r1d 2.0 true使用所有原语

It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives

我想出了这个

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);
}

}

但它输出 86.0 w0r1d 2.0 true

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

how can i make it so it doesn't add all the integers, but displays them consecutively?

推荐答案

您可以使用包装类的toString或valueOf方法将数字转换为字符串(猜猜你不在那里)然而,或者只是将所有基元填充到打印行中而没有字符串输出

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.

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

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

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).

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

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.

大部分编码不是很漂亮,但完全符合学习过程。

Most of it is not very pretty coding but will completly suffice for the learning process.

这篇关于Java打印包含多个整数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆