我如何做一个JOptionPane数组



问题问"油箱的数量只能是(2,4,8,10,15,20)";这是下面代码中的aNbrTanks。我一直在尝试使用数组来获得这些输入。但是我得到了Object不能被转换成int或者int[]不能被转换成int的错误。我需要请求JOptionPane的输入,然后再次询问它是否不符合标准。

package project2;
import javax.swing.JOptionPane;
/**
*
* @author Administrator
*/
public class VehicleApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
//name
String firstName = JOptionPane.showInputDialog("Please enter your first name");
while(firstName.equals("")){
firstName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String lastName = JOptionPane.showInputDialog("Please enter your last name");

while(lastName.equals("")){
lastName =JOptionPane.showInputDialog("Please enter a valid first name");
}
String aName = firstName + " " + lastName;

//phone
String aphone = JOptionPane.showInputDialog("Please enter your number");
while(aphone.length()!=10){
aphone = JOptionPane.showInputDialog("Please enter a valid phone number");
}
String aPhone = ("" + aphone).replaceAll("(...)(...)(....)", "$1-$2-$3");
//vechicle number
int aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Vehicles"));
while(aNbrVehicles < 1  || aNbrVehicles > 10 ){
aNbrVehicles = Integer.parseInt(JOptionPane.showInputDialog("valid number of Vehicles"));
}

//fuel tank
int aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));     



VehicleFactory JarApp = new VehicleFactory(aName, aPhone, aNbrVehicles, aNbrTanks);

JarApp.calcManufacturingCost();
JarApp.calcFuelTankCost();
JarApp.calcSubtotal();
JarApp.calcTax();
JarApp.calcTotal();
JOptionPane.showMessageDialog(null, JarApp.getSummary());
}
} 

我只是需要的想法或帮助弄清楚如何得到一个数组或语句被用作int aNbrTanks像问题问。

您可以按照您的建议在循环中请求值。我的例子展示了可以使用的循环。有更有效的方法来测试允许的值。

int aNbrTanks = 0;
while (true) {
try {
aNbrTanks = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Tanks"));the number of Vehicles"));
} catch (NumberFormatException e) {
e.printStackTrace(e);
}
if (aNbrTanks==2) {
break;
}
}

回到你的标题问题,你可以使用JOptionPane与Object[],而不是int[]。然后,它会将您的选择列表转换为JComboBox。下面是一个例子:

public static void main(String[] args) {
Object[] choices = new Object[]{2,3,5,8};
System.out.println(Arrays.toString(choices));

Object choice = JOptionPane.showInputDialog(null, "Enter the number of Tanks", "Tanks", JOptionPane.PLAIN_MESSAGE, null, choices, 2);

System.out.println(choice);
}

最新更新