It's my 2nd week in Java.
The problem:
Write an application for Cody’s Car Care Shop that shows a user a list of available services: oil change, tire rotation, battery check, or brake inspection. Allow the user to enter a string that corresponds to one of the options, and display the option and its price as $25, $22, $15, or $5, accordingly. Display Invalid Entry if the user enters an invalid item.
As you can see in my comments on bottom most part of the code, my program still produce invalid entries. Please overhaul or modify my code in order to meet the requirements(You must use parallel arrays - Prof).
import java.util.*;
public class CarCareChoice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] offers = { "oil change", "tire rotation",
"battery check", "brake inspection"};
int[] prices = {25, 22, 15, 5};
System.out.println("Enter Selection:");
String choice = input.nextLine();
for(int x = 0; x < prices.length; x){
if(offers[x].equals(choice)){
System.out.println(offers[x] " price is $" prices[x]);
}
else{
System.out.println("Invalid Entry");
}
}
}
}
//input: oil change
/*output:
oil change price is $25
Invalid Entry
Invalid Entry
Invalid Entry*/
CodePudding user response:
You can use return statement for your requirement.
import java.util.*;
public class CarCareChoice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] offers = { "oil change", "tire rotation",
"battery check", "brake inspection"};
int[] prices = {25, 22, 15, 5};
System.out.println("Enter Selection:");
String choice = input.nextLine();
for(int x = 0; x < prices.length; x){
if(offers[x].equals(choice)){
System.out.println(offers[x] " price is $" prices[x]);
return;
}
}
System.out.println("Invalid Entry");
}
}
CodePudding user response:
You want to check if the choice is either of the 4 options, try doing a break;