Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parallel Arrays in a for loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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*/

>Solution :

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");
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading