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)。 –