Java printing a string containing multiple integers

后端 未结 7 1778
别那么骄傲
别那么骄傲 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:32

    The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.

    Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of: 72 + 3 + 1 + 10.0 (which is equal to 86.0)

    String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play. In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:

        char h = 'H';  // This is a numeral! Capital H has value 72 in Ascii table
        byte three = 3;
        short one = 1;
        boolean t = true; // not a numeral
        double ten = 10;
        float two = (float) 2.0;
        long lOne = 1;
        int zero = 0;
    
        System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"  
            + zero + "r" + lOne + "d " + two + " " + t );
    

    Note how I needed to cast ten to the int-type, to lose the decimal...

    Above example is however not a good example of using string concatenations! For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:

    System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
        (int) ten, zero, lOne, two, t));
    

    Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat

    // please note: the double and the float won't print decimals!
    // note: import java.text.MessageFormat for this
    System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
        three, one, (int) ten, zero, lOne, two, t));
    

    More examples from the Ascii table.

提交回复
热议问题