Java Scanner 抛出一些我没见过的错误

标签 java runtime-error java.util.scanner

当我尝试运行我编写的这段代码时:

import java.util.Scanner;
    public class F1Calc
    {
        public static void main(String args[])
        {
            System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ".  The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm.  The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
        }
        public static String getSurface()
        {
            Scanner kb = new Scanner(System.in);
            System.out.println("What is the surface you are rolling the ball into?");
            String surface = kb.nextLine();
            kb.close();
            return surface;
        }
        public static double getMass()
        {
            Scanner kb2 = new Scanner(System.in);
            System.out.println("What is the mass of the ball in kilograms?");
            double mass = kb2.nextInt();
            kb2.close();
            return mass;
        }
        public static double getPotEnergy()
        {
            double potEnergy = getMass() * .121 * 9.8;
            return potEnergy;
        }
        public static double getMomentum()
        {
            double doublePE = 2 * getPotEnergy();
            double doublePEOverMass = doublePE / getMass();
            double velocity = Math.sqrt(doublePEOverMass);
            double momentum = velocity * getMass();
            return momentum;
        }
        public static double getCoeff()
        {
            double coeff = getPotEnergy() / (getMass() * 9.8);
            return coeff;
        }
    }

控制台显示如下:

   What is the surface you are rolling the ball into?
    Tile
    What is the mass of the ball in kilograms?
    Exception in thread "main" java.util.NoSuchElementException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at F1Calc.getMass(F1Calc.java:20)
        at F1Calc.getPotEnergy(F1Calc.java:26)
        at F1Calc.getCoeff(F1Calc.java:39)
        at F1Calc.main(F1Calc.java:6)

添加行以便我的帖子可以提交。添加行以便可以提交我的帖子。添加行以便可以提交我的帖子。添加行以便我的帖子可以提交。

最佳答案

只有一个底层 InputStream 用于 Scanner,因此不要关闭它 - 这样做会为该类的所有 future 实例关闭它,从而无法从源中读取

关于Java Scanner 抛出一些我没见过的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974454/

相关文章:

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 扫描仪被跳过

java - 在java中将json转换为excel

java - 不要在 Java Android Opengl es 2.0 中使用模板

java - 如何在 Multi-Tenancy 系统中为指定租户切换jpa方言

VB6:运行时错误 '6':溢出

java - 如何使用 poi 设置数据透视表中行标签的默认值

java - 无法获取每次创建对象时生成的随机数

SQLite:无法以编程方式打开网络文件,即使之前工作过

java - 排列发生器