我正在学习Java,并且我的知识得到了进一步的发展。我希望应用程序与用户输入的值相距更远,仅当它是正确的值时;否则,我想针对相同的问题(控制台输入)自行重复(不与应用程序相距更远),直到用户键入正确的值值!我的代码如下:
package oop.project;
import java.util.Scanner;
/**
*
* @author Dragos
*/
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);
}
构造函数类及其功能:
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) {
String input = in.nextLine();
do{
isEngineOn = true;
} while(input.equals("Yes") || input.equals("Start") || input.equals("Turn on"));
if(isEngineOn) {
System.out.println("Engine is on!");
} else {
System.out.println("Your input is not correct! Please start the engine!");
isEngineOn = false;
}
return input;
}
[在do&while之前,我在if语句中只有带有(input.equals("Yes") || input.equals("Start") || input.equals("Turn on"))
的if-else语句,但是不管用户在IDE控制台中输入了错误的单词,应用程序无论如何都会继续前进,当输入错误的单词时,它会显示正确的消息,但不会停止或限制用户键入正确的值!试图通过添加do-while语句来限制用户键入正确的值,但是效果不是很好。
您必须处于循环中,直到获得有效输入。尝试下面的代码段。
while(in.hasNext()) {
String input = in.nextLine();
if(input.equals("Yes") || input.equals("Start") || input.equals("Turn on")) {
System.out.println("Engine is on!");
break;
} else {
System.out.println("Your input is not correct! Please start the engine!");
}
}
while(!isEngineOn) {
String input = in.nextLine();
isEngineOn = input.equals("Yes") || input.equals("Start") || input.equals("Turn on"));
}