[英]How to restrict the user to enter number between certain range in java?
In Java, if you want to ask users, for example, to input numbers only between 1,000 and 100,000, the program would continue further.例如,在 Java 中,如果您希望用户只输入 1,000 到 100,000 之间的数字,则程序将继续进行。 Otherwise, ask the user to input the number again in the given range.
否则,要求用户在给定范围内再次输入数字。
Edit: Here, my program only tries to validate the input only once.编辑:在这里,我的程序只尝试验证输入一次。 How shall I make to ask the user to input until valid data(ie between 1000-100000) is entered
我该如何要求用户输入直到输入有效数据(即在 1000-100000 之间)
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Principal:");
double principal = sc.nextDouble();
if(principal<1000 || principal >100000) {
System.out.println("enter principal again:");
principal = sc.nextDouble();
}
}
You can use do-while loop here as below您可以在此处使用 do-while 循环,如下所示
public static void main(String []args){
Scanner in = new Scanner(System.in);
int result;
do {
System.out.println("Enter value bw 1-100");
result = in.nextInt();
} while(result < 0 || result > 100);
System.out.println("correct "+ result);
}
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
class Myclass {
static boolean isInteger(double number){
return Math.ceil(number) == Math.floor(number);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double num;
do{
System.out.print("Enter a integer between 1000 and 100000 : ");
num = in.nextDouble();
}
while((num < 1000 || num > 100000)||(!isInteger(num)));
System.out.println("Validated input : "+num);
}
}
Hope this helps you希望这对你有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.