简体   繁体   中英

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. 3.) if the input is not exactly the same as what is in the size array, an error message has to be printed. 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;

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.

Your for loop can be something like this

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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