ObviousAssassin
ObviousAssassin

Reputation: 11

character comparison not working

I have to write a program making a 2-D array and printing it out. Then I am supposed to guide a "character" through this maze. so I want to make it move Up/Down/Left/Right. The user would be allowed to type in u/U/d/D/l/L/r/R.

I put in so that it would give me an error if one of those was not typed in. However it still gives me an error if it is typed in correctly.

char move;                                          
    System.out.println("Which way do you want to move?  U/D/L/R");
    move=stdin.nextLine().charAt(0);
    while(move != 'u' || move !='U') {
        while( move != 'd' || move != 'D'){ 
            while( move != 'l' || move != 'L'){
                while(move != 'r' || move != 'R'){
                    System.out.println("Invalid input. Try again.");
                    move = stdin.nextLine().charAt(0);
        }}}}

Upvotes: 1

Views: 227

Answers (3)

user2030471
user2030471

Reputation:

You may also try the following (does the same thing in a different way).

Along with other field declarations:

private static final String keySet = "uUdDlLrR";

And inside the method:

char move = stdin.nextLine().charAt(0);
while (keySet.indexOf(move) == -1) {
    System.out.println("Invalid input. Try again.");
    move = stdin.nextLine().charAt(0);
}

It's just a bit more readable and requires little change in case you wish to modify the set of allowed keys.

Upvotes: 1

dreamcrash
dreamcrash

Reputation: 51413

Try this:

Scanner stdin; 
stdin = new Scanner(System.in);

move = stdin.nextLine().charAt(0);;
move  = Character.toUpperCase(move);

    while(move !='U' && move != 'D' && move != 'L' && move != 'R' ) 
    {
                    System.out.println("Invalid input. Try again.");
                    move = stdin.nextLine().charAt(0);
                    move  = Character.toUpperCase(move);
    }

Your current code do not make sense. If I type R (for example), this would make the program to enter in infinite loop. Since, all the condition on the upper while would evaluate true. Thus, not reaching the instruction that will ask for another input (stdin.nextLine()).

Upvotes: 2

sree
sree

Reputation: 183

The syntax is a little bizarre (why "while" and not "if"?.... and why nested?) ... but basically you want to be testing with '&&' not '||'.

In english: you want if input is not A and input is not B, then error. If you do "or" then it will always error because one of those nots will alway be true.

EDIT: easy mistake to make --- for style/clarity, I'd suggest:

switch (move) {
case 'u': case 'U':  
  /*up code*/    
  break;
case 'd'' case 'D':  
  /*down code*/  
  break;
case 'l'' case 'L':  
  /*left code*/  
  break;
case 'r'' case 'R':  
  /*right code*/ 
  break;
default: 
  System.out.println("Invalid input. Try again.");
  break;
}

Upvotes: 0

Related Questions