Here is my code:
double carsPrice = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of cars you would like to drive");
String [] numberOfCars = new String[sc.nextInt()];
while (numberOfCars.length > 5) {
System.out.println("Enter a number that is less than 5 and try again");
numberOfCars = new String[sc.nextInt()];
}
System.out.println("Enter the names of cars you would like to hire");
String [] chosenCarNames = new String[5];
sc.nextLine();
for (int i=0; i<numberOfCars.length; i ) {
int nameA = i 1;
System.out.println("Enter name of car " nameA);
chosenCarNames [i] = sc.nextLine();
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
if (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " nameA " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
}
}
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice = 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice = 49;
}
else {
carsPrice = 39;
}
I have made a java program that asks customers to enter the number of cars they would like to hire and after that the program should allow the user to enter the names of cars they would like to hire depending on the number of cars they would like to hire. My problem is that if the customer wants to hire more than one car, I am not able to calculate the total price the customer has to pay. If the customer wants to hire only one car, I have used if statements to calculate and display the total number of money the customer has to pay
CodePudding user response:
You could move the price calculation into the loop and accumulate it:
for (int i = 0; i < numberOfCars.length; i ) {
int nameA = i 1;
System.out.println("Enter name of car " nameA);
chosenCarNames [i] = sc.nextLine();
// Input validation omitted for brevity
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice = 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice = 49;
}
else {
carsPrice = 39;
}
}
CodePudding user response:
This is some interesting logic here:
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
If the entered value was "lamborghini", then the first part would be true, but then how could it also be equal to "toyota" and "audi" at the same time?
If the intention was to only allow "lamborghini", "toyota", or "audi 5", then move that compound boolean expression from the inner if
statement out to the while
loop, and get rid of the inner if
:
System.out.println("Enter name of car " nameA);
chosenCarNames [i] = sc.nextLine();
while (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " nameA " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}