无限次while循环在第一次执行后无法从扫描仪获取输入

时间:2018-08-22 00:44:59

标签: java

代码工作正常,但是尝试使用无限的while循环通过一次又一次地从main方法调用该方法来从用户那里获取输入,但是在第一次执行后它失败,没有抛出诸如此类的元素,请帮助我修复它,谢谢前进。

package homeWorks;

import java.util.ArrayList;
import java.util.Scanner;

public class CompareTwoLists {

    public void displayResult(){
        ArrayList<Integer> intNum = new ArrayList<Integer>();
        intNum.add(11);
        intNum.add(12);
        intNum.add(3);
        intNum.add(21);
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        list2.add(2);
        list2.add(15);
        list2.add(21);
        Scanner scan = new Scanner(System.in);
        System.out.println("Options 1: common, 2.unique in list 1, 3 unique in list 2: ");
        int comparsison=scan.nextInt();
        switch(comparsison){
        case 1:
            intNum.retainAll(list2);
            System.out.print("common values "+intNum);
            break;
        case 2:
            intNum.removeAll(list2);
            System.out.print("different values in list 1 "+intNum);
            break;
        case 3:
            list2.removeAll(intNum);
            System.out.println("diff vals in list 2 "+list2);
            break;
        default :
            System.out.println(" Enter valid input from options  ");
        }
        scan.close();
    }
    public static void main(String[] args) {
        CompareTwoLists ctl = new CompareTwoLists();
        try{
            while(true){
//here is i am facing problem
                System.out.println();
                ctl.displayResult();
                }
            }catch(Exception e)
            {e.printStackTrace();}
    }

}

输出为

选项1:通用,列表1中的2.唯一,列表2中的3,唯一: 1

common values [21]
Options 1: common, 2.unique in list 1, 3 unique in list 2: 
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 homeWorks.CompareTwoLists.displayResult(CompareTwoLists.java:20)
    at homeWorks.CompareTwoLists.main(CompareTwoLists.java:44)

0 个答案:

没有答案