【问题标题】:How to check for user input without exiting for error如何在不退出错误的情况下检查用户输入
【发布时间】:2015-10-31 15:22:44
【问题描述】:

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

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");
            }
....

【问题讨论】:

标签: java validation input


【解决方案1】:

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

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

double distance=scan.nextDouble();

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

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

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

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

【讨论】:

  • 您好,感谢您的回答。由于现阶段大学限制,我无法使用,所以可以。关于输入检查,我仍然不明白。当我按照您写的方式进行操作时,我仍然会遇到错误,据我所知,错误的输入仍然被放置在远处。我正在寻找像 C++ 中的 Isdigit 这样的东西,您可以在输入之前将其放入变量中
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
相关资源
最近更新 更多