线程" main"中的例外情况java.util.NoSuchElementException - 扫描程序

时间:2015-04-18 13:19:46

标签: java

当扫描仪在(主循环)主打印时出现时间异常:

Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Scanner.java:907)
	at java.util.Scanner.next(Scanner.java:1530)
	at java.util.Scanner.nextInt(Scanner.java:2160)
	at java.util.Scanner.nextInt(Scanner.java:2119)
	at eg.edu.alexu.csd.ds.linkedList.cs49.Polynomial.main(Polynomial.java:17)

调试代码中的

在flag = function.swit中失败(new Scanner(System.in).nextInt()); 这是代码:

public class Polynomial {
	SinglyLinkedList A = new SinglyLinkedList();
	SinglyLinkedList B = new SinglyLinkedList();
	SinglyLinkedList C = new SinglyLinkedList();
	SinglyLinkedList R = new SinglyLinkedList();
	
	public static void main(String[] args)throws Exception{
		Polynomial function = new Polynomial();
		boolean flag = true;
		while(flag){
			function.menu();
			flag = function.swit(new Scanner(System.in).nextInt());
		}
	}
	public boolean swit(int choose){
		Polynomial function = new Polynomial();
		boolean flag = true;
		switch(choose){
	    	case 1: function.setSwitch();break;
	    	case 2: function.printSwitch();break;
	    	case 3: function.addSwitch();break;
	    	case 4: function.subtractSwitch();break;
	    	case 5: function.multiplySwitch();break;
	    	case 6: function.evaluateSwitch();break;
	    	case 7: function.clearSwitch();break;
	    	default : flag = false;
	    }
		return flag;
	}

1 个答案:

答案 0 :(得分:0)

在执行nextInt()

之前,检查元素是否与hasNextInt()一致

应该是这样的

Scanner scanner = new Scanner(System.in);
int value = 0;
if(scanner.hasNextInt()) {
  value = scanner.nextInt(); 
}
flag = function.swit(value);