[英]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?
example:例子:
how to loop the input question if the inputter does not add the word 'street'如果输入者不添加“街道”一词,如何循环输入问题
It could be something like this (read the comments in code):它可能是这样的(阅读代码中的注释):
// 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);
Have you tried anything?你尝试过什么吗? If not, you can break down into the following and build up your code step-by-step.如果没有,您可以分解为以下内容并逐步构建您的代码。
You should first choose a loop to start with.您应该首先选择一个循环开始。 For-loop or Do-while loop ? For 循环还是Do-while 循环?
For a For-loop , it will repeat the logic inside the loop for a given number of times.对于For-loop ,它将重复循环内的逻辑给定的次数。
For a Do-While loop , it will repeat until your logic does not fulfil any more.对于Do-While loop ,它将重复直到您的逻辑不再满足为止。
The simplest class that can be used to read an Input will be Scanner .可用于读取 Input 的最简单的 class 将是Scanner 。
Because you know that you have to repeat your Input logic until street is being inputted at the end.因为您知道您必须重复输入逻辑,直到最后输入街道。 So you probably end up having something like this:所以你可能最终会遇到这样的事情:
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)
Note that the word automatically means that you can do nothing if your requirement is not met.请注意,自动这个词意味着如果您的要求未得到满足,您将无能为力。 Because a loop is meant to be repeat if your stated requirement is not yet finished.因为如果您规定的要求尚未完成,循环意味着重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.