簡體   English   中英

正確的Java用戶輸入

[英]Correct User Input in Java

在解決問題時,基本代碼如下所示,從用戶那里獲取4種可能的輸入,並根據輸入的內容產生響應。 但是,我需要添加一個測試以驗證是否已輸入4個可能答案中的僅1個。

我知道如何比較4個輸入中的2個,但是不能一次比較所有4個,有人可以給我一個主意嗎? 我希望自己弄清楚實際的代碼,但是指向正確方向的指針將是有益的。

因此要澄清如何-如果輸入的內容不是“賬單,通函,明信片或信件”,則產生錯誤消息X

    System.out.println("What type of Letter has been received?");
    System.out.println("Bill, Circular, Postcard or Letter");
    String Letter = kybd.nextLine();

        {
            if (Letter.equalsIgnoreCase("Bill"))  
            {
                System.out.println("Bills must be paid");
            }
            else if (Letter.equalsIgnoreCase("Circular"))
            {
                System.out.println("Circulars are thrown away");
            } 
            else if (Letter.equalsIgnoreCase("Postcard"))
            {
                System.out.println("Postcards are put on the wall");
            } 
            else if (Letter.equalsIgnoreCase("Letter"))
            {
               System.out.println("Personal letters are read and have replies written for them");
            }
        }
            if (Letter.equalsIgnoreCase("Bill"))  
            {
                System.out.println("Bills must be paid");
            }
            else if (Letter.equalsIgnoreCase("Circular"))
            {
                System.out.println("Circulars are thrown away");
            } 
            else if (Letter.equalsIgnoreCase("Postcard"))
            {
                System.out.println("Postcards are put on the wall");
            } 
            else if (Letter.equalsIgnoreCase("Letter"))
            {
               System.out.println("Personal letters are read and have replies written for them");
            }else{
            System.out.println("ERROR");
            }

您想在其中拋出“ else”條件語句,並且您可能希望查看try和catch塊,或者只是在“ else”條件中“拋出” NoSuchElement異常。

查看以下內容可能對您有用:

http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html

在else語句中引發異常非常類似於我之前的回答,而try ... catch塊幾乎就是您正在談論的測試。 因此,它可能看起來像這樣:

try
{
  Letter != "Bill"  //not exactly how it'd look, but this is a general idea on what you'd do here 
}
catch (NoSuchElementException e)
{
   System.out.println("Not a valid input.");
}

暫無
暫無

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

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