how to concatenate variables into a variable with java

后端 未结 3 1672
闹比i
闹比i 2021-01-29 09:03

I would like to concatenate a few variables into a string variable but I am unable to get it to work. When I compile it says \"not a statement\" and \"; expected.\"



        
相关标签:
3条回答
  • 2021-01-29 09:54
    String resW = a + " + " + b;
    

    try this..

    0 讨论(0)
  • 2021-01-29 09:54

    Instead of using resW, you could try this:

    public class QuickTester {
    
        public static void main(String[] args) {
    
            float a = 1;
            float b = 2;
    
            System.out.println(String.format("%.0f + %.0f", a, b));
            System.out.println(String.format("%.2f + %.2f", a, b));
            System.out.println(String.format("%.5f + %.5f", a, b));
        }
    }
    

    Output:

    1 + 2
    1.00 + 2.00
    1.00000 + 2.00000
    

    Note:

    • If you insist, you could do something like String resW = String.format(...);
    • String#format can help you 'beautify' your resulting string, allowing you to specify the number of decimal places, alignment, etc
    0 讨论(0)
  • 2021-01-29 10:01
    resW = a + " + " + b;
    

    Use a plus sign to concatenate Strings.

    It should allow an autoconversion from float to String, but if it doesn't, you can change the floats to Floats, and do:

    resW = a.toString() + " + " + b.toString();
    
    0 讨论(0)
提交回复
热议问题