Very simple problem that I can't seem to wrap my head around.
I'm writing a bicycle program that calculates MPH based on the cadence and gears set on the bike.
The gears that can be set are between 1-3 and the cadence is between 1-100.
TL;DR If a user enters a number outside of that range, I'm having trouble figuring out how to have the program prompt them again until they enter the correct range. I'm also having trouble figuring out how to get the entire BicycleTest program to loop over once the calculations are finished.
I looked up other questions and noticed a bunch of people talking about while loops, which I tried, but I must have done it incorrectly because it did not loop to the beginning. I'm leaving it at my original if-else loop but I would appreciate help on how to properly use a while loop for this situation.
Code below:
public class Bicycle
{
// instance variables declared private
private int gear;
private int cadence;
private int speed;
//accessor (get) method for gear
public int getGear()
{
return gear;
}
//set method for gear
public void setGear(int gear)
{
if (gear >=1 && gear <= 3)
{
this.gear = gear;
}
else
{
System.out.println ("Sorry, please enter a number between 1-3");
}
}
//accessor (get) method for cadence
public int getCadence()
{
return cadence;
}
//set method for cadence
public void setCadence(int cadence)
{
if (cadence >=1 && cadence <=100)
{
this.cadence = cadence;
}
else
{
System.out.println ("Sorry, please enter a number between 1-100");
}
}
//accessor (get) method for speed
public int getSpeed()
{
if (gear == 1)
{
return cadence / 12;
}
else if (gear == 2)
{
return cadence / 6;
}
else if (gear == 3)
{
return cadence / 4;
}
else
{
return 0;
}
}
} // end of main
and then here is the BicycleTest code:
import java.util.Scanner;
public class BicycleTest
{
public static void main(String[] args)
{
Bicycle bike = new Bicycle();
Scanner input = new Scanner(System.in);
System.out.println("Enter the gear :");
bike.setGear(input.nextInt());
System.out.println("Enter the cadence :");
bike.setCadence(input.nextInt());
int speed = bike.getSpeed();
System.out.println ("Your speed in MPH is: ");
System.out.println(speed);
}
}
Aucun commentaire:
Enregistrer un commentaire