在这部分代码中,扫描仪要求用户输入1到5之间的数字.我需要为一堆变量重写这个,所以有什么方法可以缩短它?
if (Q1 != 1 || Q1 != 2 || Q1 != 3 || Q1 !=4 || Q1 != 5) {
System.out.println("Error: Please enter a number between 1 and 5.");
}
Run Code Online (Sandbox Code Playgroud)
而不是键入Q1 != 1或2或3等,有没有办法写1-5或类似的东西?
我在一段旧代码之后建模了一个while循环,因为我有点忘了怎么做.这是旧作品:
Scanner s2 = new Scanner(System.in);
Q1 = s2.nextDouble();
while (Q1 < 1 || Q1 > 5) {
System.out.println("");
System.out.println("ERROR: Please enter a number between 1 and 5.");
System.out.println("");
System.out.println(question1);
Q1 = s2.nextDouble();
}
Run Code Online (Sandbox Code Playgroud)
这很简单.这是我现在写的那篇文章:
System.out.println("Welcome to " + appName + "!");
System.out.println("To begin, please select a username.");
Scanner usernameScanner = new Scanner(System.in);
String username = usernameScanner.nextLine();
System.out.println("Your username will be " + username + ".");
System.out.println("Is that correct?");
while(username.length() < 3){
System.out.println("Error: Your username must be more than 3 …Run Code Online (Sandbox Code Playgroud) java ×2