创建外部Car类和驱动程序CarDemo类。更改CarDemo类的说明包括两个方法(getInputYear()返回1940年到2016年之间的年份,getInputMake()返回汽车的品牌并检查空字符串)。
它编译时没有错误,但它只询问年份模型输入,然后自己打印出其他所有内容。
public class Car
{
private int yearModel;
private String make;
private int speed;
// initialize variables
Car(int y, String m)
{
yearModel = y;
make = m;
speed = 0;
}
// setYear method
public void setYearModel(int y)
{
yearModel = y;
}
// setMake method
public void setMake(String m)
{ make = m;
}
// set speed method
public void setSpeed(int s)
{
speed = s;
}
// getYearModel method
public int getYearModel()
{
return yearModel;
}
// getMake method
public String getMake()
{
return make;
}
// getSpeed method
public int getSpeed()
{
return speed;
}
// accelerate method accelerates the car's speed by 5
public void accelerate()
{
speed += 5;
}
// brake method decreases the car's speed by 5
public void brake()
{
speed -= 5;
}
}
这是DemoCar类
import java.util.Scanner;
public class CarDemo
{
public static void main(String[] args)
{
Car yourCar;
String make;
double yearModel, speed;
Scanner sc = new Scanner(System.in);
System.out.print("What is the car's year model? ");
yearModel = sc.nextDouble();
System.out.print("What is the make of the car? ");
make = sc.nextLine();
yourCar = new Car(0, make);
System.out.println("Current status of the car:");
System.out.println("Year model: " + yourCar.getYearModel());
System.out.println("Make: " + yourCar.getMake());
System.out.println("Speed: " + yourCar.getSpeed());
// Accelerate the car five times.
System.out.println("Speed up!");
System.out.println();
for(int i=0; i<5; i++)
{
yourCar.accelerate();
System.out.println("demoCar's speed " + yourCar.getSpeed());// Display the speed.
}
System.out.println();
// Brake the car five times.
System.out.println("Slow down!");
System.out.println();
for(int i=0; i<5; i++)
{
yourCar.brake();
System.out.println("demoCar's speed " + yourCar.getSpeed());// Display the speed.
}
}
}
答案 0 :(得分:2)
sc.nextDouble();
没有处理换行符,而你的sc.nextLine()
消耗了它,并跳过其余部分。
您可以再添加一个nextLine()
来捕获剩余的换行符。
System.out.print("What is the car's year model? ");
yearModel = sc.nextDouble();
boolean isInRange = (1940 <= yearModel) && (yearModle <= 2016);
if(!isInRange){
// not in range
return;
}
sc.nextLine(); // consumes the left-over newline character.
System.out.print("What is the make of the car? ");
make = sc.nextLine();
<强>替代地强>:
System.out.print("What is the make of the car? ");
make = sc.nextLine();
将sc.nextLine()
更改为sc.next()
方法next()
找到并返回此扫描程序中的下一个完整令牌。