请求部分的java输出字
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");
}
}
用户只需输入服务的前3个字母,即可获得他们输入的服务及其匹配价格。这是到目前为止我的代码
# 1 楼答案
这看起来不像是我会使用的方法,它不是用户友好的(IMHO),还有其他解决方法(按我认为最好的解决方法排序)
使用带有预定义选项的
showInputDialog
,看起来像JComboBox
使用一个自定义的
JPanel
将作为消息传递,并使用JRadioButton
以便用户可以选择其中一个(当然,您可以更改layout manager使其看起来不同最后是一种丑陋的方式,要求用户编写它,并使用^{} 对} 方法(这是您试图实现的):
services
变量和userInput
变量进行比较,使用^{它们都产生了与此类似的输出:
注释/取消注释每个方法以查看它们的行为,并相应地选择生成上述每个输出的代码:
重要提示:
您的程序也没有放在Event Dispatch Thread (EDT)上,这可能会在将来导致一些线程问题,因此请确保将您的所有程序放在其中,就像我放在Event Dispatch Thread (EDT)上一样: