我的讲义中有以下示例代码。在我的代码中,如果你试图直接打印一个,你会得到一个与我想要的不匹配的输出。如何打印我刚选择的车辆清单。不显示任何其他行。但如果输入小于1且超过3,则显示错误消息
package scanner1;
import java.util.Scanner;
public class Scanner1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int carSelect;
int [] noNumb = {1,2,3};
String [] carList = {"Lexus","Bugati","McLaren"};
System.out.println("================ Car List ================");
for (int i = 0; i < noNumb.length; i++) {
System.out.println(noNumb [i]+". "+carList[i]);
}
System.out.println(" ");
System.out.print("Choose your car : ");
carSelect = scan.nextInt ();
loop:
for (int i=0; i<noNumb.length; i++){
if(carSelect == noNumb [i]){
System.out.println("Great you choose " +carList[i]);
break;
}else if (carSelect <= noNumb[i]){
System.out.println("Your input is less than 1 ");
break;
} else {
System.out.println("Wrong input ");
}
}
} }
输出:
================ Car List ================
1. Lexus
2. Bugati
3. McLaren
Choose your car : 3
Wrong input
Wrong input
Great you choose McLaren
BUILD SUCCESSFUL (total time: 1 second)
答案 0 :(得分:1)
从你的问题来看,我认为这就是你要找的东西:
if (carSelect < 1){
System.out.println("Your input is less than 1 ");
} else if (carSelect > 3) {
System.out.println("Wrong input ");
} else {
//valid input, let us check the car selected
System.out.println("Great you choose " +carList[carSelect]);
}