2016-10-23 11 views
0

ユーザーはサービスの最初の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"); 

    } 
} 

答えて

0

if(validChoices[x].startsWith(careChoice))を使用してください。

+0

長さのチェックが良いかもしれません – user

+0

@userこれを追加すると範囲外のエラーが発生します – Alex204

+0

@ Alex204おそらく 'x'は配列の長さよりも長くなります。議論されたFor Eachループを使用する方が安全です(http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work)。 –

関連する問題