0

User should only have to input the first 3 letters of the service and get the service they entered and its matching price.

Here is my code so far, during research I saw things about using range or index. I'm thinking I need to use range but how do I accomplish this with String value?

import javax.swing.*;
public class CarCareChoice2
{
   public static void main(String[] args)
   {
     final int NUM_OF_ITEMS = 8;
     String[] validChoices = {"oil change", "tire rotation", "battery check", "brake inspection"};
     int[] prices = {25, 22, 15, 5};
     String strOptions;
     String careChoice;
     double choicePrice = 0.0;
     boolean validChoice = false;
     strOptions = JOptionPane.showInputDialog(null, "Please enter one of the following care options: oil change, tire rotation, battery check, or brake inspection");
     careChoice = strOptions;
     for(int x = 0; x < NUM_OF_ITEMS; ++x)
     {
        if(careChoice.equals(validChoices[x]))
        {
           validChoice = true;
           choicePrice = prices[x];
        }
     }
     if(validChoice)
        JOptionPane.showMessageDialog(null, "The price of a(an) " + careChoice + " is $" + choicePrice);
     else
        JOptionPane.showMessageDialog(null, "Sorry - invalid entry");

   }
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Alex204
  • 45
  • 8

2 Answers2

0

Use if(validChoices[x].startsWith(careChoice)).

Mike Lowery
  • 2,630
  • 4
  • 34
  • 44
  • @Alex204 Most likely `x` is greater than the length of your array. It's safer to use a For Each loop as discussed [here](http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work). – Mike Lowery Oct 27 '16 at 17:51
0

The class I am in uses Mindtap and the sandbox simulation doesn't allow for the JOption GUI. I was able to figure it out and get it to work. So here is the properly working code using Scanner inputs.

import java.util.*;
public class CarCareChoice2
{
   // Modify the code below
   public static void main (String[] args)
   {
      Scanner input = new Scanner(System.in);
      boolean isMatch = false;
      String[] items =  { "oil change", "tire rotation",
         "battery check", "brake inspection"};
      int[] prices = {25, 22, 15, 5};
      int x;
      int matchIndex = 0;
      String menu = "Enter selection:";
      for(x = 0; x < items.length; ++x)
        menu += "\n   " + items[x];
      System.out.println(menu);
      String selection = input.nextLine();
      for (x = 0; x < items.length; x++)
      if(selection.substring(0, 2).equals(items[x].substring(0,2)))
      {
      isMatch = true;
      matchIndex = x;
      }
      if(isMatch)
          System.out.println(selection + " price is $" + prices[matchIndex]);
      else
          System.out.println("Invalid Entry");
  }
}
Foof
  • 1