Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printing a string containing multiple integers

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.

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

i came up with this

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

}

but it outputs 86.0 w0r1d 2.0 true

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

like image 480
user2650243 Avatar asked Mar 23 '23 22:03

user2650243


1 Answers

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.

like image 179
morgano Avatar answered Apr 16 '23 10:04

morgano