4

This is just a part of my code that I have problem troubleshooting.

static int checkConcat(String number) {
        TreeSet<Integer> a = new TreeSet<Integer>();
        for(int i=0; i<number.length(); i++) {
            a.add(Integer.parseInt(number.charAt(i)));
        }
}

The error that I'm getting is :

error: incompatible types: char cannot be converted to String

What's wrong with the code, and how can I solve it in this context?

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

4 Answers4

6

You can easily convert the char to String.

char aCharacter = 'c';
String aCharacterAsString = String.valueOf(aCharacter);

So in your case:

a.add(Integer.parseInt(String.valueOf(number.charAt(i))));
George Z.
  • 6,643
  • 4
  • 27
  • 47
3

Integer.parseInt(String s) has the argument type String, not char as returned by number.charAt(i).

Convert to a String:

a.add(Integer.parseInt("" + number.charAt(i)));
0

A single character is char, not String. Although you could construct a single-character string from char using a method described below, parsing a number digit-by-digit should be done with a different API:

for(int i=0; i<number.length(); i++) {
    a.add(Character.digit(number.charAt(i), 10));
}

To construct a single-character string from char in Java, use String.valueOf method:

String singleDigit = String.valueOf(number.charAt(i));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

charAt returns one character of the string, therefore the return type is char not string to convert to string use the String.valueOf method:

String.valueOf(number.charAt(i))

Or don't use Integer.parse just subtract '0' from the character to convert it to the digit value. This would be a simpler more efficient way to convert a single digit value.

number.charAt(i) -'0'
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • The trick of subtracting zero character, borrowed from C, was foreign to Java since day one, because Java standard library has `Character.digit` method. To be honest, I was unaware of its existence for many years, diligently writing `ch-'0'` in my Java code. – Sergey Kalinichenko Jan 26 '18 at 13:24