您好,我们的任务是创建一个程序,该程序接受用户提供的三个正整数,即 x、y 和 i。程序将显示 x 和 y 之间所有能被 i 整除的数字。因此,x 和 i 必须小于 y。如果用户输入了无效的输入,程序必须再次提示他输入有效的值。
import java.util.Scanner;
public class TrialD {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int x = 0;
int y = 0;
int i = 0;
System.out.print("Enter x: ");
x = sc.nextInt();
System.out.print("Enter y: ");
y = sc.nextInt();
System.out.print("Enter i: ");
i = sc.nextInt();
if((x<y)&&(i<y)) {
for(int c = x; c < y; c++) {
if(c % i == 0) {
System.out.print(c + " ");
}
}
}
else System.out.println("Invalid Input!");
}
}
最佳答案
添加一个while循环,直到输入正确。
import java.util.Scanner;
public class TrialD {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
book correct = false;
int x = 0;
int y = 0;
int i = 0;
while(!correct) {
System.out.print("Enter x: ");
x = sc.nextInt();
System.out.print("Enter y: ");
y = sc.nextInt();
System.out.print("Enter i: ");
i = sc.nextInt();
if((x<y)&&(i<y)) {
correct = true;
for(int c = x; c < y; c++) {
if(c % i == 0) {
System.out.print(c + " ");
}
}
}
else System.out.println("Invalid Input!");
}
}
}
关于java - 如何再次提示用户输入有效值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693028/