In: Computer Science
public static char inputDirection() : Functionality: The user will be asked to input ‘u’ for up, ‘d’ for down, ‘l’ for left or ‘r’ for up. And in case the user enters anything except one of these four letters, it will be kept asked to enter a new char until the entered char matches one of them.
(in java)
*note (do just complete this specific method as this is just one of the methods apart of this.)
import java.util.*;
class Hello {
public static boolean compare(char c) {
// comparing with u
int p = Character.compare(c, 'u');
// comparing with d
int q = Character.compare(c, 'd');
// comparing with l
int r = Character.compare(c, 'l');
// comparing with r
int s = Character.compare(c, 'r');
// returing true when we see u,d,l,r
if ((p == 0) || (r == 0) || (q == 0) || (s == 0)) {
return true;
} else
return false;
}
public static char inputDirection() {
Scanner sc = new Scanner(System.in);
char c;
do {
System.out.print("Please enter u for up , d for down, l for left and r for right: ");
// reading the character
c = sc.next().charAt(0);
if (!compare(c)) {
System.out.println("Please try again!");
}
// while the given char is not u,d,l,r repeat asking
} while (!compare(c));
return c;
}
public static void main(String[] args) {
char x = inputDirection();
}
}
output: