java - 如何检查用户输入而不退出错误

标签 java validation input

我需要检查用户输入,如果该值不是数字,则要求提供正确的输入。但是,当我执行此代码时,程序会显示一条错误消息,然后崩溃 - 它不会要求用户提供新的输入。如何解决这个问题?谢谢你!

import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
    public static void main (String [] args)
    {
        final int MAX=100, feet=12, meter=100;
        final double inch=2.54;
        Scanner scan = new Scanner (System.in);
        System.out.println ("This program converts distances. ");
        System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
        double distance=scan.nextDouble();
        if (!scan.hasNextDouble())
            {
                System.out.println ("please enter a numeric value");
                distance=scan.nextDouble();
            }
        int unitType = scan.nextInt();
        if (distance<0)
            {
                System.out.println ("Please enter a non negative distance");
            }
....

最佳答案

只需在执行 scan.nextDouble() 之前带上 if 子句即可。

 if (!scan.hasNextDouble())
 {
   System.out.println ("please enter a numeric value");
   scan.nextLine();
   distance=scan.nextDouble();
 }

double distance=scan.nextDouble();

首先确保要读取的数字是double值,然后再读取。你正在做相反的事情

scan.nextLine()在这里做什么?

假设用户输入abc 2scan.hasNextDouble() 检查接下来要读取的标记是否为 double 值。事实并非如此,因此 scan.hasNextDouble() 的计算结果为 false 并且 if 子句被执行。在 if 子句中,有 scan.nextLine()。它只是丢弃来自 scan 的当前输入,从而刷新 scan。如果您不这样做,则 scan 仍包含 abc 2 并且在执行 distance = scan.nextDouble() 时,编译器会发出错误。

最好将 if 替换为 while。假设用户输入错误。您的程序检查输入并发现它不是 double 值。如果执行 if 子句,系统会要求用户输入一个数值。如果用户再次输入错误怎么办?这次,你会得到一个错误。使用 while 循环使您的程序不断询问用户正确的输入,直到他输入数值。

关于java - 如何检查用户输入而不退出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453222/

相关文章:

java - 如何将数据库引用与响应式(Reactive) Spring Data MongoDB 一起使用?

xml - 如何验证 XML

c# - 在 Code First 的情况下使用 MetadataType 强制执行验证是否有意义?

angularJS textAngular输入框输入文本后失去焦点

java - 写入 Zip 中的子目录?使用 java.util.zip。 ZipEntry.putNextEntry()

java - Android 中的自定义 View 在每个设备上看起来都不同

java - 使用类路径

javascript - 为什么第一个 If 'is Not' 语句不起作用?

python - input() 在进程中不起作用

php - 在文本框中显示值以使用 ajax 和 php 进行编辑