簡體   English   中英

如何在數據輸入中添加必須寫入的單詞,如果不輸入單詞則數據會出現循環?

[英]how to add words that must be written in data input, if the word is not input then a loop will occur in the data?

例子:

  1. Input your address [must be ended with 'street']: red 輸入必須以'street'結尾!
  2. 輸入您的地址[必須以'street'結尾]:red street

如果輸入者不添加“街道”一詞,如何循環輸入問題

可能是這樣的(閱讀代碼中的注釋):

// Keyboard input Stream. The JVM will auto-Close this when app ends.
Scanner userInput = new Scanner(System.in);  
    
// To hold supplied Address.
String address = "";
    
// Continue looping for as long as the `address` variable is empty.
while (address.isEmpty()) {
    System.out.print("Enter Address: -> ");  // Ask User for Adress:
    address = userInput.nextLine().trim();   // Get entire keyboard input line:
    /* Validating User Input using the String#matches() method and a
       small Regular Expression (RegEx): `(?i)` Letter case insensative,
       `.*` Any number of alphanumerical characters, ` street` must 
       end with a whitespace and `street` in any letter case.      */
    if (!address.matches("(?i).* street")) {
        // Not a match! Inform User and allow to try again...
        System.out.println("Invalid Address. Must end with the word "
                             + "'Street'. Try Again...");
        System.out.println();
        address = "";  // Empty `address` to ensure reloop.
    }
}

// If we get to this point then validation was successful.
    
// Display the Address in Console Window:
System.out.println("Supplied Address: -> " + address);

你嘗試過什么嗎? 如果沒有,您可以分解為以下內容並逐步構建您的代碼。

使用哪個循環?

您應該首先選擇一個循環開始。 For 循環還是Do-while 循環
對於For-loop ,它將重復循環內的邏輯給定的次數。
對於Do-While loop ,它將重復直到您的邏輯不再滿足為止。

什么 function 可以用來讀取輸入?

可用於讀取 Input 的最簡單的 class 將是Scanner

代碼會是什么樣子?

因為您知道您必須重復輸入邏輯,直到最后輸入街道 所以你可能最終會遇到這樣的事情:

Define some useful variables here if necessary
Loop Body Start (Repeat Condition here if you choose for-loop)
  Ask for Input
Loop Body End (Repeat Condition here if you choose do-while loop)

請注意,自動這個詞意味着如果您的要求未得到滿足,您將無能為力。 因為如果您規定的要求尚未完成,循環意味着重復。

暫無
暫無

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

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