当我第二次使用它时,Java Scanner无法正常工作

时间:2017-07-28 17:43:59

标签: java java.util.scanner

当我在Java第二次使用Scanner时,扫描仪sc2的对象不能转换为此字符串中的整数" int typeOfSort = sc2.nextInt();"。

Eclipse在启动程序之前不显示错误,但在启动后显示此错误。程序可以运行,但是当sc2必须转换为int的字符串时,programm显示错误。如何解决?

"
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 Buble.main(Buble.java:39)
"

Java代码

 import java.util.Scanner; 

 public class Buble {


  public static void main(String[] args) {

    int size;    // size of Array
    int array[]; // Array

    System.out.print("Enter size of arrays: ");
    // Scanner is tool for input text to console
        Scanner sc = new Scanner(System.in);        
        size = sc.nextInt();
        array = new int [size];
        sc.close();

    for(int i = 0; i < array.length; i++){
        double randnum = Math.floor(Math.random() * 1000);
        array[i] = (int) randnum;
        System.out.println("Element " + i + " = " + (int) randnum);

    }

    for(int b = 0; b < array.length; b++){
        for(int i = 1; i < array.length; i++) {
            if(array[i] < array[i-1]){
                int a = array[i];
                array[i] = array[i-1];
                array[i-1] = a;
            }

        }
    }

    System.out.println("If you want to sort from smallest to largest 
     press 1 or 2 if Conversely: ");

        Scanner sc2 = new Scanner(System.in);
        int typeOfSort = sc2.nextInt(); // String with error
        sc2.close();

    if(typeOfSort == 1){
        for(int i = 0; i < array.length; i++){
            System.out.println(array[i]);
        }
    }
    else{
        for(int i = array.length; i < array.length; i++){
            System.out.println(array[i]);
        }
    }
        }
     }

1 个答案:

答案 0 :(得分:-1)

你正在使用多个扫描仪而你正在对其中一个对象进行sc.close(); ..这就是异常的原因

请记住:当你关闭其中一个扫描仪时,这就是关闭输入流(在所有其他扫描仪上共享)之后,尝试从剩余的扫描仪实例读取任何内容都会引发异常