本文介绍了Java仅接受来自使用Scanner的用户的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解如何仅接受来自用户的数字,并且我尝试使用try catch块这样做,但我仍然会遇到错误。

I am trying to understand how to only accept numbers from the user, and I have attempted to do so using try catch blocks, but I would still get errors with it.

    Scanner scan = new Scanner(System.in);

    boolean bidding;
    int startbid;
    int bid;

    bidding = true;

    System.out.println("Alright folks, who wants this unit?" +
            "\nHow much. How much. How much money where?" );

    startbid = scan.nextInt();

try{
    while(bidding){
    System.out.println("$" + startbid + "! Whose going to bid higher?");
    startbid =+ scan.nextInt();
    }
}catch(NumberFormatException nfe){

        System.out.println("Please enter a bid");

    }

我想了解它为什么不起作用。

I am trying to understand why it is not working.

我通过在控制台输入一个来测试它,我会收到错误,而不是希望请输入出价决议。

I tested it out by inputting a into the console, and I would receive an error instead of the hopeful "Please enter a bid" resolution.

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Auction.test.main(test.java:25)


推荐答案

使用 Scanner.nextInt()时,会导致一些问题。当您使用 Scanner.nextInt()时,它不会消耗新行(或其他分隔符)本身,因此返回的下一个标记通常是空字符串。因此,您需要使用 Scanner.nextLine()来关注它。你可以放弃结果。

While using Scanner.nextInt(), it causes some problems. When you use Scanner.nextInt(), it does not consume the new line (or other delimiter) itself so the next token returned will typically be an empty string. Thus, you need to follow it with a Scanner.nextLine(). You can discard the result.

因为这个原因,我建议总是使用 nextLine (或 BufferedReader.readLine())并在使用 Integer.parseInt()后进行解析。您的代码应如下所示。

It's for this reason that I suggest always using nextLine (or BufferedReader.readLine()) and doing the parsing after using Integer.parseInt(). Your code should be as follows.

        Scanner scan = new Scanner(System.in);

        boolean bidding;
        int startbid;
        int bid;

        bidding = true;

        System.out.print("Alright folks, who wants this unit?" +
                "\nHow much. How much. How much money where?" );
        try
        {
            startbid = Integer.parseInt(scan.nextLine());

            while(bidding)
            {
                System.out.println("$" + startbid + "! Whose going to bid higher?");
                startbid =+ Integer.parseInt(scan.nextLine());
            }
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Please enter a bid");
        }

这篇关于Java仅接受来自使用Scanner的用户的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 23:47