0

I've created an interactive class that solves kinematic equation problems (accessed in another class within a user input loop: mathiverse) that works just fine, but after the answer is given it throws a NoSuchElementException.

I have tried moving where I close my scanner, but it hasn't worked and I'm pretty sure the issue is with how my Kinematic class functions within my input loop.

My user input loop and kinematic constructor (not within the same class):

while(!(input.equals("exit")))
{
    if(input.equals("help"))
    {
        System.out.println("~ Commands ~");
        System.out.println("help - brings up a list of 
        commands(what you're reading)");
        System.out.println("kinematic - solves a kinematic 
        equations problem; requires input of known and unknown 
        variables");
        System.out.println("exit - closes the program");
        System.out.println("~~~~~~~~~~~~");
    }

    //user decides to explore kinematic options
    if(input.equals("kinematic"))
    {
        Kinematic calc = new Kinematic();

        System.out.println(calc.answer());
    }

    input = scan.nextLine();
}

public Kinematic()
{
    Scanner scanMath = new Scanner(System.in);

    System.out.println("If you are solving for the variable, enter \"?\", 
    if the variable is not given, enter a space.");
    System.out.println("Enter the acceleration: ");
    acc = scanMath.nextLine();

    System.out.println("Enter the displacement: ");
    disp = scanMath.nextLine();

    System.out.println("Enter the initial velocity: ");
    init = scanMath.nextLine();

    System.out.println("Enter the final velocity: ");
    fin = scanMath.nextLine();

    System.out.println("Enter the time: ");
    time = scanMath.nextLine();

    scanMath.close();
}

After the answer is given, I would like my code to continue searching for input, but it throws this message:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651) at Mathiverse.main(Mathiverse.java:53)

Andrew Regan
  • 5,087
  • 6
  • 37
  • 73

1 Answers1

0

When closing scanner from Kinematic, you close the System.in stream as well. Use the same scanner in both your main method and Kinematic.

Take a look at : java.util.NoSuchElementException - Scanner reading user input

Martin'sRun
  • 522
  • 3
  • 11