gpt4 book ai didi

java - 了解嵌套循环和类

转载 作者:行者123 更新时间:2023-12-01 18:07:28 25 4
gpt4 key购买 nike

我启动了一个项目来理解深度嵌套的循环和类。在我的 CYCLING 方法中,当我到达 if(y >= 0) 循环时,它没有正确使用类中的变量。例如,如果 MPH 为 15,档位为 1 或 3,它不会要求我换档。或者如果档位为 1 并且速度为 11+,它不会要求我换档?我做错了什么?

<小时/>
public class Bike {
int speed;
int gear;

void changeGear(int newVal) {
gear = newVal;
}

void speedUp(int newVal) {
speed = newVal;
}

void breaks(int slow) {
speed = speed + slow;
}

void printState() {
System.out.println("Gear is: " + gear);
System.out.println("Speed is: " + speed + ("MPH"));
}
}

//________________________

public static boolean cycle = true;
public static Bike b1 = new Bike();
public static int x;
public static int y;
public static Scanner input = new Scanner(System.in);
public static int choice;

//______________________________

public static void cycling() {
while (cycle == true) {
System.out.println("What would you like to do now? Enter a number.");
System.out.println("1: Speed Change");
System.out.println("2: Change Gear");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Choose a speed change");
y = input.nextInt();
if (y < 0) {
b1.breaks(y);
if (b1.speed < 0) {
b1.speed = Math.abs(y) + y;
System.out.println("You've stopped entirely");
}
}
if (y >= 0) {
b1.speed = y;
b1.printState();
if (b1.speed >= 0 && b1.speed <= 10) {
while (b1.gear != 1) {
System.out.println("You need to be in Gear 1 for " + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
if (b1.speed >= 11 && b1.speed <= 20) {
while (b1.gear != 2) {
System.out.println("You need to be in Gear 2 for" + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
if (b1.speed >= 21) {
while (b1.gear != 3) {
System.out.println("You need to be in Gear 3 for" + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
}
/*if(b1.speed >= 0 && b1.speed <=10){
b1.gear = 1;
}else if(b1.speed >= 11 && b1.speed <=20){
b1.gear = 2;
}else if(b1.speed >= 21){
b1.gear = 3;
}*/
b1.printState();
}
}
}
}
}
}

最佳答案

考虑一下你的陈述。你的东西基本上看起来像这样:

if (b1.speed >= 0 && b1.speed <= 10) {
//some while loop here to do whatever
if (b1.speed >= 11 && b1.speed <= 20) {
//more code
}
}

在您的代码中,此声明永远不会成立:

if (b1.speed >= 11 && b1.speed <= 20) {

获得该语句的唯一方法是 if b1.speed>=0 && b1.speed<=10。因此,当您到达第二个(嵌套)if 语句时,b1.speed 会在 11 到 20 之间吗?

关于java - 了解嵌套循环和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com