简体   繁体   中英

Why is the program printing numbers when the variable is a string?

I'm trying to write a method that will take a string like "abcd" and then print out each character twice so that the output will be "aabbccdd". So far, this is the code I have:

String abcd = "abcd";
    String t = "";

    for (int i = 0; i < abcd.length(); i++){
        t = t + (abcd.charAt(i) + abcd.charAt(i));
    }
    for (int j = 0; j < abcd.length(); j++){
        System.out.printf("%s\n",t);
    }

The code above prints out numbers and I don't understand why. Shouldn't it print out the letters since all the variables are strings?

The variables are strings, but charAt returns a char , which is a kind of number, and then you're adding those numbers together, which leaves you with an int . Use a StringBuilder instead and append the result of charAt twice.

See Binary Numeric Promotion from Java Language Specification .

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. If any operand is of a reference type, it is subjected to unboxing conversion.

  2. Widening primitive conversion is applied to convert either or both operands as specified by the following rules:

    • If either operand is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

class Test {
    public static void main(String[] args) {
        int i = 0;
        float f = 1.0f;
        double d = 2.0;
        // First int*float is promoted to float*float, then
        // float==double is promoted to double==double:
        if (i * f == d) System.out.println("oops");

        // A char&byte is promoted to int&int:
        byte b = 0x1f;
        char c = 'G';
        int control = c & b;
        System.out.println(Integer.toHexString(control));

        // Here int:float is promoted to float:float:
        f = (b == 0) ? i : 4.0f;
        System.out.println(1.0 / f);
    }
}

For your particular use case removing the parenthesis should be enough. By using them you force char addition to happen first.

Just remove the parenthesis like this:

t = t + abcd.charAt(i) + abcd.charAt(i);

Otherwise the char values are numerically added according to their ASCII value when retrieved using charAt(i) .

you can change that line to

t += abcd.charAt(i) + (abcd.charAt(i) + "");

so that you can get its string value.

public class Test {

public static void main(String[] args) {
    String s = "abcd";
    String t ="";

    for (int i = 0; i < s.length(); i++){
        t = t + s.charAt(i) + s.charAt(i);
    }
    for (int j = 0; j < s.length(); j++){
        System.out.printf("%s\n",t);
    }
}

}

Ok, straight to the code:

String txt = "abcd";
StringBuilder sb = new StringBuilder();

char c;
for (int i = 0; i < txt.length(); i++){
    c = txt.charAt(i);
    sb.append(c).append(c);
}
System.out.printf("%s\n", sb.toString());
  • StringBuilder - when you are going to concatenate strings or characters, especially when concatenating long strings, use StringBuilder. It does not create a copy of the string every time, when you append.
  • Character addition - Bax's answer already pointed this out. Primitive data types in Java :

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\' (or 0) and a maximum value of '\￿' (or 65,535 inclusive).

Which explains what you received as result of the addition.

String charDouble(String str){

   StringBuilder sb = new StringBuilder();
   for(int i=0; i< str.length(); i++){
     sb.append(str.chatAt(i));
     sb.append(str.charAt(i));
   }
   return sb.toString();

   //Alternatively you could just print it here.
   //System.out.println(sb.toString());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM