Home > Back-end >  Why does my scanner object only allow me to get input from System.in once?
Why does my scanner object only allow me to get input from System.in once?

Time:02-04

The first time my scanner object is used to take user input, it works perfectly fine. However, from that point forward, whenever I try to take input from System.in, I run into a NoSuchElementException. Does anyone know how to fix this so that I can get input from a user multiple times?

Here's my code:

package com.company;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Practice
{

    static Scanner inputScanner;

    public static void main(String[] arg)
    {
        inputScanner = new Scanner(System.in);

        System.out.println("Enter the number of elements you would like sorted: ");
        int size = inputSize();

        System.out.println("Enter "   size   " integers to be sorted.");
        int[] arr = makeArray(size, inputScanner);
    }


    public static int inputSize() throws InputMismatchException
    {
        try (Scanner s = new Scanner(System.in))
        {
            int size = s.nextInt();
            s.close();
            if (size > 0)
                return size;
        }
        catch (InputMismatchException e)
        {
            System.out.println("User input must be a numerical value.");
            System.exit(0);
        }

        System.out.println("The size of the list must be positive.");
        System.exit(0);
        return 0;
    }

    public static int[] makeArray(int size, Scanner s)
    {
        int[] arr = new int[size];
        for (int i = 0; i < size - 1; i  )
            arr[i] = s.nextInt();
        return arr;
    }

    public void SelectionSort(int[] arr)
    {
        for (int i = 0; i < arr.length; i  )
        {
            int j, minIndex;
            for (j = i   1, minIndex = i; j < arr.length; j  )
                if (arr[j] < arr[minIndex])
                    minIndex = j;
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

CodePudding user response:

Because you are using a try-with-resources here

try (Scanner s = new Scanner(System.in))

that will close the Scanner s and System.in. Don't do that.

Scanner s = new Scanner(System.in);
try

Should fix your issue. System.in is a global. Don't close it.

  •  Tags:  
  • Related