在哪里以及如何编码我的 "Invalid Input"
Where and How to code my "Invalid Input"
我需要创建一个程序来执行以下操作:
1.) 要求用户从 S、M、L、X 中选择
2.) 显示所选尺寸以及相应的价格。
3.) 如果输入与大小数组中的内容不完全相同,则必须打印一条错误消息。到目前为止,我能够获得用户输入并显示其相应的价格。但是,我对在何处以及如何放置错误消息的语法有疑问。
我只允许使用 import javax.swing.JOptionPane 来完成所有这些。
import javax.swing.JOptionPane;
public class PizzaChoice{
public static void main(String[]args){
char [] size = {'S','M','L','X'};
double [] total = {6.99, 8.99, 12.50, 15.00};
char userInput = ' '; //hold the size that user will choose
userInput = JOptionPane.showInputDialog("Sizes Available: S, M, L, X").charAt(0); //ask user to type in his/her choice of pizza size
for(int i=0; i<size.length; i++){
if(userInput == size[i]){
JOptionPane.showMessageDialog(null, userInput+" = "+total[i]);
}
}
}
}
您可以使用 flag
来确定用户是否输入了正确的内容。
你的 for
循环可以是这样的
int flag=0; //initial value for your flag
for(int i=0; i<size.length; i++){
if(userInput == size[i]){
JOptionPane.showMessageDialog(null, userInput+" = "+total[i]);
flag=1; //states that user entered correct value
}
}
//check here if user input was correct or not
if(flag==0){
//display the error message here
}
希望这对您有所帮助:)
我需要创建一个程序来执行以下操作: 1.) 要求用户从 S、M、L、X 中选择 2.) 显示所选尺寸以及相应的价格。 3.) 如果输入与大小数组中的内容不完全相同,则必须打印一条错误消息。到目前为止,我能够获得用户输入并显示其相应的价格。但是,我对在何处以及如何放置错误消息的语法有疑问。
我只允许使用 import javax.swing.JOptionPane 来完成所有这些。
import javax.swing.JOptionPane;
public class PizzaChoice{
public static void main(String[]args){
char [] size = {'S','M','L','X'};
double [] total = {6.99, 8.99, 12.50, 15.00};
char userInput = ' '; //hold the size that user will choose
userInput = JOptionPane.showInputDialog("Sizes Available: S, M, L, X").charAt(0); //ask user to type in his/her choice of pizza size
for(int i=0; i<size.length; i++){
if(userInput == size[i]){
JOptionPane.showMessageDialog(null, userInput+" = "+total[i]);
}
}
}
}
您可以使用 flag
来确定用户是否输入了正确的内容。
你的 for
循环可以是这样的
int flag=0; //initial value for your flag
for(int i=0; i<size.length; i++){
if(userInput == size[i]){
JOptionPane.showMessageDialog(null, userInput+" = "+total[i]);
flag=1; //states that user entered correct value
}
}
//check here if user input was correct or not
if(flag==0){
//display the error message here
}
希望这对您有所帮助:)