我有一个获取并返回一个字符输入的静态函数。 然后它将使用while循环检查输入。 我的主要方法获得输入后,结果将相应地显示给用户输入。Java - 获取用户输入并通过开关盒传输到主函数
下面是我的方法:
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
char choice = getInput(sc);
String result;
switch (choice)
{
case ('a'): result = "u choose A";
break;
}
}
private static char getInput(Scanner keyboard)
{
Scanner sc = new Scanner(System.in);
System.out.println("a, b, c, d, e, q: ");
char choice = sc.nextLine().trim().toLowerCase().charAt(0);
while (choice != 'a' || choice != 'b' || choice != 'c' || choice != 'd' || choice != 'e' || choice != 'q')
{
System.out.println("You have entered an invalid entry.");
System.out.println("a, b, c, d, e, q: ");
choice = sc.nextLine().trim().toLowerCase().charAt(0);
}
return choice;
}
}
不过,我正在即使我输入的字符“A”输入无效的结果。
我可以知道哪部分出了问题吗?
作为一种改进,您可以使用“键盘”而不是在getInput方法内创建新的Scanner对象。 –