Java printing a string containing multiple integers

后端 未结 7 1786
别那么骄傲
别那么骄傲 2021-01-19 08:16

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

7条回答
  •  情歌与酒
    2021-01-19 08:29

    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 one and 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:

    String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
    

    In this second case your expression will start with a String object, evaluating the rest of the operations as 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.

提交回复
热议问题