[英]Why does my scanner object only allow me to get input from System.in once?
我的扫描仪 object 第一次用于接受用户输入时,它工作得非常好。 但是,从那时起,每当我尝试从 System.in 获取输入时,都会遇到 NoSuchElementException。 有谁知道如何解决这个问题,以便我可以多次获得用户的输入?
这是我的代码:
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;
}
}
}
因为你在这里使用了try-with-resources
try (Scanner s = new Scanner(System.in))
这将close
Scanner s
和System.in
。 不要那样做。
Scanner s = new Scanner(System.in);
try
应该解决你的问题。 System.in
是一个全局. 不要关闭它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.