When writing Java code, often encounter the situation is the input is wrong to do? Most of the thinking is to use an if judgment, but if you judge it, we can not let the user input again, because the IF statement program will exit the program directly after execution. Therefore, in order to realize the loop, it is necessary to use while () to put the input statement inside to implement the loop. There are two ways to enter:
<1> use string input--use this to enter only strings and then convert to the one you want
BufferedReader bf = new BufferedReader (new InputStreamReader (system.in)); Bf.readline (); <2> use scanner, this word also only input string will not error, if you define as input integer type, then input other types of words will error, so to speak scanner itself is an exception. The following are examples of: 1, while () to determine whether the input is correct, and the opportunity to enter the second time---this is also the use of scanner there is no longer an example of this method is used to determine whether the second input string is the first time to input strings
private void replacemethed () {
Scanner s = new Scanner (system.in);
System.out.println ("= = = Welcome to use = = =")
System.out.print ("Please enter a string:");
String str = S.next ();
while (true) {
System.out.print ("Please enter a string of strings above:");
String subStr = S.next ();
int index = Str.indexof (SUBSTR);
As long as the index is not 1, the string that is entered later is a string of the preceding strings
if (Index! =-1) {
String substitution, replacing substr with "Hello"
str = Str.replaceall (subStr, "Hello");
System.out.println ("Replaced string:" + str);
Break
} else {
SYSTEM.OUT.PRINTLN ("You entered the wrong string, please re-enter!") ");
}
}
}
2. BufferedReader input
BufferedReader bf = new BufferedReader (new InputStreamReader (system.in));
String startTime = null; The input of the machine between the
Date startdate = null; When the format is converted, between the machines
while (true) {
try {
System.out.print ("Please enter the machine time (hh:mm format):");
StartTime = Bf.readline ();
StartDate = Sdf.parse (startTime);
If there is no output, jump out of the loop
Break
} catch (ParseException e) {
SYSTEM.OUT.PRINTLN ("Format error, please restart time (hh:mm format):");
}
Summary of input methods for Java