Home > Back-end >  Java problem for solutions
Java problem for solutions

Time:10-07

From the keyboard to enter a positive integer n (if the input data is not in conformity with the requirements, to remind users to input, until they meet the requirements), and for solving all odd Numbers between 1 to n,
Ask: what add statements can solve the input data does not conform to remind user to input and know that meet the conditions of

CodePudding user response:

int sum=0;
Scanner reader=new Scanner (System. In);
System. The out. Println (" please enter a positive integer: ");
While (true) {
String String=reader. NextLine ();
String regEx1="\ \ d +";
The Pattern p;
The Matcher m;
P=Pattern.com running (regEx1);
M=p. atcher (string);
If (m.m atches ()) {
For (int I=1; I & lt;=Integer. The valueOf (string); I++) {
The sum +=I;
I +=2;
}
System.out.println(sum);
return;
} else {
System. The out. Println (" input is not a positive integer, please input again: ");
}
}

CodePudding user response:

reference response: 1/f friendship dream
int sum=0;
Scanner reader=new Scanner (System. In);
System. The out. Println (" please enter a positive integer: ");
While (true) {
String String=reader. NextLine ();
String regEx1="\ \ d +";
The Pattern p;
The Matcher m;
P=Pattern.com running (regEx1);
M=p. atcher (string);
If (m.m atches ()) {
For (int I=1; I & lt;=Integer. The valueOf (string); I++) {
The sum +=I;
I +=2;
}
System.out.println(sum);
return;
} else {
System. The out. Println (" input is not a positive integer, please input again: ");
}
}

In the for loop should not require i++ iteration
  • Related