搜索并行数组以匹配值

时间:2016-10-23 16:52:21

标签: java arrays

有一个可供选择的服务列表,我需要用户从列表中输入服务,然后输出他们选择的内容和费用。

这是我的代码,它编译正确,我只是不明白为什么每当我输入数组中输入框中的内容时,它一直输出无效输入。

有什么想法吗?

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

   }
}

3 个答案:

答案 0 :(得分:0)

您无法在Java中将字符串与==进行比较。

这会有效:

validChoices[x].equals(careChoice)

答案 1 :(得分:0)

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

   }
}

您无法将String==进行比较。相反,您必须使用String.equals()方法。

答案 2 :(得分:0)

我希望这是您正在寻找的最佳答案。

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;
      int 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 = Integer.valueOf(strOptions);
      System.out.println("care choice :" + careChoice);
      if(careChoice < validChoices.length){
        validChoice = true;
        choicePrice = prices[careChoice-1];
      }
     if(validChoice)
        JOptionPane.showMessageDialog(null, "The price of a " + careChoice + " is $" + choicePrice);
     else
        JOptionPane.showMessageDialog(null, "Sorry - invalid entry");

   }
}

希望这有效:)