【发布时间】:2019-12-09 20:54:57
【问题描述】:
我希望使用 while 循环限制整数值的输入,在某些值之间,其中包含几个 if-else if-else 语句!它有点工作,但不完全是它应该......也想过使用开关,但我太“绿色”不知道怎么做!如果有人愿意并且知道如何......我也欢迎使用开关!如果需要,甚至是嵌套开关...... 这是我的代码:
public class OOPProject {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
Car Honda = new Car(2018, 20000, "Honda", "Civic", 200, 6, 0, 0);
System.out.println("Manufacturer is: " + Honda.maker + ", model: " + Honda.model +
", year of fabrication: " + Honda.year + ", price: " + Honda.price + "!");
System.out.println("Please start the engine of your vehicle, by typing in 'Yes' or 'Start' or 'Turn on'!");
System.out.print("Do you wish to start the engine?");
System.out.println(" ");
Honda.StartEngine(sc);
//System.out.println("Engine is on!");
System.out.println("Do you wish to depart? Shift in to the first gear then and accelerate!");
System.out.println("Type in the speed: ");
Honda.accelerate(sc);
System.out.println("We are departing! Shifting in to " + Honda.currentGear +
"st gear and accelerating to " + Honda.currentSpeed + " km per hour!");
}
构造函数和函数:
public class Car {
public int year;
public int price;
public String maker;
public String model;
public int maximumSpeed;
public int numberOfGears;
public int currentSpeed;
public int currentGear;
public boolean isEngineOn;
public Car(int year, int price, String maker, String model, int maximumSpeed,
int numberOfGears, int currentSpeed, int currentGear) {
this.year = year;
this.price = price;
this.maker = maker;
this.model = model;
this.maximumSpeed = maximumSpeed;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
}
public String StartEngine(Scanner in) {
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
isEngineOn = true;
System.out.println("Engine is on!");
return input;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
return null;
}
public int accelerate(Scanner in){
while(in.hasNextInt()){
currentSpeed = in.nextInt();
if(isEngineOn && currentSpeed > 0){
currentGear++;
} else if(currentSpeed > 50){
System.out.println("We cannot accelerate to more than 50 km per hour, when shifting in the 1st gear!");
} else{
System.out.println("We cannot depart at 0 km per hour!");
}
}
return 0;
}
}
它正在接受输入,但它并没有像它应该的那样走得更远,它也没有给出错误消息或停止应用程序,我的错误是什么?
【问题讨论】:
-
重点是,如果用户输入0,则给出0 km/h错误信息,如果用户输入超过50,则给出“太多”错误信息。基本上我想将用户可以输入的整数值限制在 1 到 50 之间。不允许输入 50+,并且扫描程序必须一遍又一遍地显示错误消息,直到用户输入正确的值。跨度>
-
关于
switch:您应该仅将其用于切换,而不是用于条件检查。请参阅this answer 了解更多信息。 -
@user85421 所以你基本上是在说nextInt() 和nextLine(),不要接吻和化妆...??我应该将 int 转换为字符串吗?
-
@user85421 好吧,我在最后指定了:“它正在接受输入,但它没有按照应有的方式进一步处理它,它也没有给出错误消息或停止应用程序”
-
引用:“除非计划一些额外的功能”......我是! =)
标签: java