使用缩短的字符串从数组中查找字符串值

时间:2016-10-23 22:28:51

标签: java arrays range

用户只需输入服务的前3个字母,即可获得他们输入的服务及其匹配价格。

到目前为止,这是我的代码,在研究期间,我看到了使用范围或索引的事情。我想我需要使用范围,但如何使用String值完成此操作?

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

   }
}

2 个答案:

答案 0 :(得分:0)

使用if(validChoices[x].startsWith(careChoice))

答案 1 :(得分:0)

我所在的类使用Mindtap,并且沙盒模拟不允许使用JOption GUI。我能够弄清楚并使其正常工作。因此,这是使用扫描器输入的正确工作代码。

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