【问题标题】:I'm trying to make my program throw an IllegalArgumentException if the input is not a number如果输入不是数字,我试图让我的程序抛出 IllegalArgumentException
【发布时间】:2018-03-22 18:11:08
【问题描述】:

如果输入不是数字并且我无法弄清楚,我正在尝试使其成为可能会抛出我的异常,有人可以帮助我走上正确的轨道

import java.util.Scanner;

    class calculations
    {

        public static void main(String[] args)
        {
            Scanner scan = new Scanner(System.in);
            int number;
            int total = 0;
            try
            {

            } catch ( IllegalArgumentException e)
            {
                //error
            }
            while (true)
            {
                number = scan.nextInt();

                if (number == 0)
                {
                    break;
                }
                total += number;
            }
            System.out.println("Total is " + total);
        }

    }

【问题讨论】:

  • 你在抓IllegalArgumentException 而不是扔它
  • 定义“数字”。
  • 为什么你认为try...catch 块会这样做?
  • Throw exception in Java的可能重复
  • 整数或任何数字,即浮点数?

标签: java


【解决方案1】:

您应该使用hasNextInt,这将允许您检查流中的下一个标记是否可以解析为 int。

if (! scanner.hasNextInt()) throw new IllegalArgumentException()

【讨论】:

  • 我已经有一段时间没有用 Java 编程了,但是如果下一个项目是“.”的话,那会起作用吗? (句号)?
  • 是的,它应该检查是否存在 int。一个 '。'不是 int,所以希望不会有问题。
猜你喜欢
  • 1970-01-01
  • 2021-02-04
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 2011-07-15
  • 2021-07-27
相关资源
最近更新 更多