java 如何添加数据输入中必须写入的字,如果该字未输入,则数据中会出现循环?

xesrikrc  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(123)

示例:
1.输入您的地址[必须以"street"结尾]:红色输入必须以'street'结尾!
1.输入您的地址[必须以"street"结尾]:雷德斯特里特
如果输入者没有添加单词"street",如何循环输入问题

wz8daaqr

wz8daaqr1#

可能是这样的(阅读代码中的注解):

// 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);
t2a7ltrp

t2a7ltrp2#

你尝试过什么吗?如果没有,你可以分解成以下几个步骤,一步一步地构建你的代码。

使用哪个循环?

您应该首先选择一个循环作为开始。For-loopDo-while loop
对于For-loop,它将在循环内重复逻辑给定的次数。
对于Do-While循环,它将重复执行,直到您的逻辑不再满足。

什么函数可用于读取输入?

可用于读取Input的最简单类是Scanner

代码将是什么样子?

因为你知道你必须重复输入逻辑,直到最后输入了street,所以你可能会得到这样的结果:

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)

注意,单词automatically意味着如果你的要求没有被满足,你什么也不能做,因为循环意味着如果你的要求还没有完成,循环就会被重复。

相关问题