简体   繁体   English

在哪里以及如何编码我的“无效输入”

[英]Where and How to code my “Invalid Input”

I need to create a program that will do the following: 1.) ask user to choose from S, M, L, X 2.) display the chosen size together with the corresponding price. 我需要创建一个程序来执行以下操作:1.)要求用户从S,M,L,X中进行选择。2.)显示选定的尺寸以及相应的价格。 3.) if the input is not exactly the same as what is in the size array, an error message has to be printed. 3.)如果输入与size数组中的输入不完全相同,则必须打印一条错误消息。 So far I am able to get the user input and display it's corresponding price. 到目前为止,我已经能够获得用户输入并显示其相应的价格。 However, I'm having a problem with where and how to place the syntax for my error message. 但是,我在哪里以及如何放置错误消息语法的问题。

I am only allowed to use import javax.swing.JOptionPane for all of this. 我只允许对所有这些使用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]);
        }
    }
}

} }

You can use a flag to determine if the user has entered the correct input or not. 您可以使用flag来确定用户是否输入了正确的输入。

Your for loop can be something like this 您的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
  }

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM