首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对“无效输入”进行编码

如何对“无效输入”进行编码
EN

Stack Overflow用户
提问于 2016-05-29 04:22:13
回答 1查看 59关注 0票数 0

我需要创建一个程序来完成以下工作:1)要求用户从S,M,L,X2中选择。)显示所选择的大小和相应的价格。3.)如果输入与大小数组中的输入不完全相同,则必须打印错误消息。到目前为止,我能够得到用户的输入,并显示它的相应价格。但是,我对如何放置错误消息的语法有问题。

我只允许对所有这些使用导入javax.swing.JOptionPane。

代码语言:javascript
复制
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]);
        }
    }
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-29 04:27:08

您可以使用flag来确定用户是否输入了正确的输入。

您的for循环可以是这样的

代码语言:javascript
复制
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
  }

希望这会有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37506128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档