CR9191
CR9191

Reputation: 51

In Java, why does char ch disagree with String command?

When I'm writing codes for my switch statement, I declared this for receiving input along with new class of Array,

    ArrayList list = new ArrayList();

    Scanner s = new Scanner(System.in);

    printCommands();

    while(s.hasNext())
    {
        String command = s.next();
        char ch = command.charAt(0);

but when I'm in the while loop, for case "a" (add integer to array), this line disagreed because ch is declared as char and eclipse suggested to switch it as string, but it still causes error.

switch(command)
        {
            case "c":
                list.clear();
            return;

            case "a":
                ch = s.next(); //s.next() gets the error due to ch?
                list.add(ch);

Upvotes: 0

Views: 119

Answers (3)

Aify
Aify

Reputation: 3537

A char is not a String. scan.next() returns a String. If you want to get new input and use the first character in that new input as ch, I suggest using:

char ch = scan.next().charAt(0);

However, since in your question you are stating that you want to add the integer to the array, i suggest using

int intToAdd = scan.nextInt();

eg: this should work for you

ArrayList list = new ArrayList();

Scanner s = new Scanner(System.in);

while (s.hasNext()) {
    String command = s.next();
    char ch = command.charAt(0);
    switch (command) {
        case "c":
            list.clear();
            return;
        case "a":
            ch = s.next().charAt(0); // no more error
            list.add(ch);
            break;
        case "e":
            // this will print all of the array just for testing purposes
            System.out.println(list.toString());
            break;
    }
}

Upvotes: 4

egelev
egelev

Reputation: 1205

The Scanner#next() method return type is String. That is why you can not assign its result to a char variable. And you already have used that:

String command = s.next();

You can not use the same method and assign its result to a char.

ch = s.next(); //s.next() gets the error due to ch?

Upvotes: 1

Óscar López
Óscar López

Reputation: 236114

Try this:

switch(ch) {
case 'c':
// ...
case 'a':
// ...

It's a char, not a String you're dealing with. Notice the single quotes!

Upvotes: 1

Related Questions