0
用戶只需輸入服務的前3個字母並獲得他們輸入的服務及其匹配的價格。使用縮短的字符串從數組中查找字符串值
這是我的代碼到目前爲止,在研究期間我看到了有關使用範圍或索引的事情。我想我需要使用範圍,但我怎麼用字符串值來完成這個?
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");
}
}
也許一個長度檢查也會很好 – user
@user當我添加這個時,我得到一個越界錯誤 – Alex204
@ Alex204最有可能'x'大於你的數組長度。使用For Each循環更安全(在這裏討論)(http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work)。 –