簡體   English   中英

在哪里以及如何編碼我的“無效輸入”

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

我需要創建一個程序來執行以下操作:1.)要求用戶從S,M,L,X中進行選擇。2.)顯示選定的尺寸以及相應的價格。 3.)如果輸入與size數組中的輸入不完全相同,則必須打印一條錯誤消息。 到目前為止,我已經能夠獲得用戶輸入並顯示其相應的價格。 但是,我在哪里以及如何放置錯誤消息語法的問題。

我只允許對所有這些使用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
  }

希望這可以幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM