简体   繁体   English

使用Scanner读取Float时发生Eclipse错误

[英]Eclipse error when using Scanner to read a Float

As part of a training exercise I'm coding a project to simulate a vending machine, and when I take in a float value Eclipse throws the following errors: 作为培训的一部分,我正在编码一个项目以模拟自动售货机,当我采用浮点值时,Eclipse会引发以下错误:

The error in question occurs in this block of code: 有问题的错误发生在以下代码块中:

public void Restock() {
            boolean done = false;
            Float price;
            String quit, name;
            Scanner scan = new Scanner(System.in);
            scan.useLocale(Locale.US);
            scan.useDelimiter("\\n");

            while (!done) {
                System.out.println("Enter Item Name: ");
                name = scan.next();
                System.out.println("Enter Price (XX.XX): $");
                price = scan.nextFloat();
                item = new Items(name, price);
                stock.add(item);
                System.out.println("Quit? (Y/N): ");
                quit = scan.next();
                while (!quit.equalsIgnoreCase("y") && !quit.equalsIgnoreCase("n")) {
                    System.out.println("Invalid Entry. Quit? (Y/N): ");
                    quit = scan.next();
                }
                if (quit.equalsIgnoreCase("y")) {
                    done = true;
                } else if (quit.equalsIgnoreCase("n")) {
                    done = false;
                }
            }
            scan.close();
        }

I've tried running the code without the delimiter, adding an additional 'scan.nextLine();' 我尝试在不使用定界符的情况下运行代码,并添加了额外的“ scan.nextLine();” statement above 'price = scan.nextFloat();' “ price = scan.nextFloat();”上方的语句 and in that case on the second pass through the loop it skipped asking for the name and went right to the price. 在那种情况下,在第二次通过循环时,它跳过了询问名称的过程,直接转到价格上。 Can somebody help me figure this out? 有人可以帮我解决这个问题吗?

Your question does not provide a lot of information. 您的问题没有提供很多信息。 However, here's my quickest attempt at recreating your code: 但是,这是我重新创建代码的最快尝试:

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class RestockDemo {
    public ArrayList<Items> stock = new ArrayList<Items>();

    public static void main(String[] args) {
        RestockDemo restockDemo = new RestockDemo();
        restockDemo.restock();
    }

    public void restock() {
        boolean done = false;
        float price;
        String quit, name;
        Scanner scan = new Scanner(System.in);
        scan.useLocale(Locale.US);
        scan.useDelimiter("\\n");

        while (!done) {
            System.out.print("Enter Item Name: ");
            name = scan.next();
            System.out.print("Enter Price (XX.XX): $");
            price = scan.nextFloat();

            Items item = new Items(name, price);
            stock.add(item);
            System.out.println(stock.get(0).name);
            System.out.println(stock.get(0).price);

            System.out.print("Quit? (Y/N): ");
            quit = scan.next();
            while (!quit.equalsIgnoreCase("y") && !quit.equalsIgnoreCase("n")) {
                System.out.print("Invalid Entry. Quit? (Y/N): ");
                quit = scan.next();
            }
            if (quit.equalsIgnoreCase("y")) {
                done = true;
            } else if (quit.equalsIgnoreCase("n")) {
                done = false;
            }
        }
        scan.close();
    }

    class Items {
        public String name;
        public double price;
        Items(String name, double price) {
            this.name = name;
            this.price = price;
        }
    }
}

I tried Bakna's solution in Eclipse and it worked of course. 我在Eclipse中尝试了Bakna的解决方案 ,它当然起作用了。 Accepting a string instead and parsing it as a float is probably a nice quick fix. 相反,接受一个字符串并将其解析为浮点数可能是一个不错的快速解决方案。

Nevertheless, the weird thing I experienced when experimenting with your code was that when I ran the code above with the original scan.nextFloat implementation on NetBeans, it worked. 但是,我在尝试使用您的代码时遇到的奇怪的事情是,当我在NetBeans上使用原始scan.nextFloat实现运行以上代码时,它起作用了。 On the other hand, a java.util.InputMismatchException occurs when I try the code in Eclipse. 另一方面,当我在Eclipse中尝试代码时,会发生java.util.InputMismatchException。

Here are the different outputs: 以下是不同的输出:

NetBeans: NetBeans:

run:
Enter Item Name: Lilly Pulitzer Pearl Romper
Enter Price (XX.XX): $198.88
Lilly Pulitzer Pearl Romper
198.8800048828125
Quit? (Y/N): y
BUILD SUCCESSFUL (total time: 8 minutes 0 seconds)

Eclipse: 日食:

Enter Item Name: Lilly Pulitzer Pearl Romper
Enter Price (XX.XX): $198.89
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextFloat(Unknown Source)
    at RestockDemo.restock(RestockDemo.java:26)
    at RestockDemo.main(RestockDemo.java:11)

Frankly, I'm surprised to find that two different development environments can produce inconsistent results and I'm curious to find out why. 坦白说,我很惊讶地发现两个不同的开发环境会产生不一致的结果,并且我很想知道原因。 I am assuming it has something to do the new line delimiter, but I'm not sure. 我假设它可以做换行符,但是我不确定。

While your question skips over a lot of information on how the class and everything else works, a possible source of your errors is that you are using a Float to store your value, but using nextFloat() to get your value, which returns a float . 尽管您的问题跳过了有关类以及其他所有内容如何工作的大量信息,但错误的可能根源是您正在使用Float来存储您的值,但使用nextFloat()来获取您的值,这将返回一个float Shouldn't be an issue, but you never know. 应该不成问题,但您永远不会知道。 Regardless, a solution you may try (which is how it always works for me) in that instance is to replace scan.nextFloat() with Float.valueOf(scan.next()) so you don't have to depend on finicky autoboxing at all. 无论如何,在这种情况下,您可以尝试的解决方案(这始终对我有效)是用Float.valueOf(scan.next())替换scan.nextFloat() ,因此您不必依赖挑剔的自动装箱完全没有

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM