-1

I am trying to coding Java and adding a char to an array. My idea is compare two char, if they are different, I will add them to an array and here is my code.

ArrayList<String> different = new ArrayList<>();
if (character.charAt(i) == (character.charAt(i+1))) 
{
}
else
{
    different.add(character.charAt(i+1));
}

But when I run my code, they said to me that "no suitable method found for add (char)" at line 6, and I can not run the code. Could you please give me some ideas? Thank you very much for your help.

2

4 Answers 4

1

The problem is that you are adding char datatype to an arraylist which is of type String. You need to change the code to:

ArrayList<Character> different = new ArrayList<>();
if (character.charAt(i) != (character.charAt(i + 1))) {
    different.add(character.charAt(i + 1));
}
Sign up to request clarification or add additional context in comments.

Comments

0

String::charAt returns a char, not a String. So your char cannot be put into a list holding String objects. Square peg, round hole.

Also char is a legacy type, limited to a subset of less than half of the over 110,000 characters defined in Unicode, restricted to code points in the “basic plane”. You should learn to work with code points as numbers to be able to handle any Unicode characters.

Comments

0

When you declared List<String> or ArrayList<String>, it means the List should contain type String or literals(something between double quote "". FYI, this is called Generic Type.

Use String#valueOf(char c) to create new String from a char. Example:-

//returns a type char
char c = character.charAt(i+1);

//use String#valueOf(char c) to create new `String` from variable `c`
different.add(String.valueOf(c));

** Oracle has good tutorial on Generic Type, you could refer to it. https://docs.oracle.com/javase/tutorial/java/generics/index.html

Comments

0

ArrayList<Character> different = new ArrayList<>();

if (character.charAt(i) == (character.charAt(i+1))) { } else { different.add(character.charAt(i+1)); }

///////////////////

Just add Wrapper class Character instead of String.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.