Alex204 Alex204 - 1 month ago 11
Java Question

Searching parallel arrays for matching values

There is a list of services to choose from, I need the user to enter a service from the list and it outputs what they chose and the cost.

This is my code, it compiles correctly, I just don't understand why it keeps outputting invalid input every time when I type in exactly what is in the array into the input box.

Any ideas?

import javax.swing.*;
public class CarCareChoice
{
public static void main(String[] args)
{
final int NUM_OF_ITEMS = 4;
String[] validChoices = {"oil change", "tire rotation", "battery check", "brake inspection"};
double[] 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 == validChoices[x])
{
validChoice = true;
choicePrice = prices[x];
}
}
if(validChoice)
JOptionPane.showMessageDialog(null, "The price of a " + careChoice + " is $" + choicePrice);
else
JOptionPane.showMessageDialog(null, "Sorry - invalid entry");

}
}

Answer
import javax.swing.*;
public class CarCareChoice
{
   public static void main(String[] args)
   {

      // ...

      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 " + careChoice + " is $" + choicePrice);
     else
        JOptionPane.showMessageDialog(null, "Sorry - invalid entry");

   }
}

You cannot compare Strings with ==. Instead, you must use the String.equals() method.