// 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);
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)
2条答案
按热度按时间wz8daaqr1#
它可能是这样的(阅读代码中的注解):
t2a7ltrp2#
你尝试过什么吗?如果没有,你可以分解成以下几个步骤,一步一步地构建你的代码。
使用哪个循环?
您应该首先选择一个循环作为开始。For-loop或Do-while loop?
对于For-loop,它将在循环内重复逻辑给定的次数。
对于Do-While循环,它将重复执行,直到您的逻辑不再满足。
什么函数可用于读取输入?
可用于读取Input的最简单类是Scanner。
代码将是什么样子?
因为你知道你必须重复输入逻辑,直到最后输入了street,所以你可能会得到这样的结果:
注意,单词automatically意味着如果你的要求没有被满足,你什么也不能做,因为循环意味着如果你的要求还没有完成,循环就会被重复。