By default Scanner uses one or more whitespaces as delimiter, which separates tokens, so next
returns token representing entire word, not single characters.
If you want next
to return single non-whitespace characters then you can set delimiter to
- series of whitespaces (
\s+
in regex where \
needs to be written as "\\"
in String)
or
But since zero
OR one or more of X
is same as zero or more of X
, instead of +
which in regex means "one or more occurrences", we can use *
which represents "zero or more occurrences". So regex representing our delimiter may look like \s+
(which in String literal needs to be written as "\\s+"
since \
needs to be escaped)
Demo:
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\s*");
System.out.println("Enter commands U(up),D(down),L(left),R(right)");
String command = scan.next();
if (command.equalsIgnoreCase("U")) {
System.out.println("Do this");
} else if (command.equalsIgnoreCase("D")) {
System.out.println("Do that");
} else {
System.out.println("unknown command: "+ command);
}
Based on your comment it looks like you want to handle group of commands passed as one word like UDULR
which should move up, down, up, left and finally right. In that case you could organize your code like:
private void moveUp(){
//code for moving up:
System.out.println("moving up");
}
private void moveDown(){
//... similar
}
//rest of moving methods...
Now you can add one more method which will let chose which method to use based on char we pass to it:
public void move(char dirrection){
switch(dirrection){
case 'U' : moveUp(); break;
case 'D' : moveDown(); break;
case 'L' : moveLeft(); break;
case 'R' : moveRight(); break;
default: System.out.println("can't move in dirrection: "+dirrection);
}
}
Now in your code you should be able to use something like:
System.out.println("Enter commands U(up),D(down),L(left),R(right)");
String command = scan.next();
for (char directionCommand : command.toCharArray()){
move(directionCommand);
}