62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.Scanner;
//输入一个数,显示一个数,输入错误重新输入
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double temp;
while (true) {
System.out.print("输入:");//输入一个数
while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
System.out.print("输入错误,重新输入:");
sc.nextLine();//释放掉输入内容
}
temp = sc.nextDouble();//在输入正确的情况下接受数字
System.out.println(temp);
}
}
}
Scanner sc = new Scanner(System.in);
double temp;
while (true) {
System.out.print("输入:");//输入一个数
while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
String line= sc.nextLine();//释放掉输入内容
if(line.isEmpty())
break;
try {
Double.parseDouble(line);
} catch (Exception e) {
break;
}
System.out.println();
System.out.print("输入错误,重新输入:");
}
temp = sc.nextDouble();//在输入正确的情况下接受数字
System.out.println(temp);
}
Scanner sc = new Scanner(System.in);
double temp;
while (true) {
System.out.print("输入:");//输入一个数
while (!sc.hasNextDouble()) {//如果输入的不是数字,进入循环
String line= sc.nextLine();//释放掉输入内容
if(line.isEmpty())
continue;
System.out.print("输入错误,重新输入:");
}
temp = sc.nextDouble();//在输入正确的情况下接受数字
System.out.println(temp);
}