无法在Java中重新使用scaner.in!为什么?

时间:2019-03-27 16:04:54

标签: java java.util.scanner

我试图多次重用一个功能。每次它要求用户输入“选择”(一个仅包含1个符号的字符串)时,其数字都从1到6。当我第一次使用它时,它就可以使用了,但是之后我就不能再使用Scanner了。我不明白-为什么?

这是我使用的功能(哪里有问题)

public static String Choice_function() {       
    Scanner sc = new Scanner(System.in);

    System.out.println("1 - create list");
    System.out.println("2 - fill list with random values");
    System.out.println("3 - delete one element from list");
    System.out.println("4 - analyse of the list");
    System.out.println("5 - check how many odd nubers are in list");
    System.out.println("6 - exit");
    System.out.println("To choose enter digit according to jour choice: ");
    if(sc.hasNextLine()) {
        String choice = sc.next();            
        //sc.nextLine();  // Consume newline left-over
        sc.close();
        return choice;
    }
    sc.close();
    return null;
}

这是主要功能

 public static void main(String[] args){
    int ListLength;
    String choice;
    boolean isListCreated = false;
    LinkedList<Integer> list;
    System.out.println("Greetings for entering in this program!");        
    choice = Choice_function();
        switch(choice) {
            case "1":
                System.out.println("1. choice");
                isListCreated = true;
                choice = Choice_function();
                break;
            case "2":
                System.out.println("2. choice");
                choice = Choice_function();
                break;
            case "3":
                System.out.println("3. choice");
                choice = Choice_function();
                break;
            case "4":
                System.out.println("4. choice");
                choice = Choice_function();
                break;
            case "5":
                System.out.println("5. choice");
                choice = Choice_function();
                break;
            case "6":
                System.out.println("Thank you and goodbye!");
                break;
              default:
                System.out.println("User input error.");
                choice = Choice_function();
                break;
          }   
}

我希望先输入“ Enter digit:”,然后输入3,然后再输入“”和“ Enter digit:”,然后我实际上可以再输入一次4、5,或我想要的任何数字

0 个答案:

没有答案