当前位置: 代码迷 >> J2SE >> Scanner上next()和nextInt()的有关问题
  详细解决方案

Scanner上next()和nextInt()的有关问题

热度:9804   发布时间:2013-02-25 00:00:00.0
Scanner下next()和nextInt()的问题

package cc.openhome;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Average3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum = 0;
int count = 0;
int number;
while (true) {
try {
number = scanner.nextInt();
if (number == 0) {
break;
}
sum += number;
count++;
} catch (InputMismatchException e) {
System.out.printf("略过非整数输入: %s%n", scanner.next());
} //为什么这里使用.nextInt()会出错?
}
System.out.printf("平均 %.2f%n", sum / count);
}
}



------最佳解决方案--------------------------------------------------------
你注释的这个位置,显然已经是解析 int 失败的情况了,继续用 nextInt() 当然只能继续失败。。。

需要用 next() 来跳过当前待处理的输入信息。
------其他解决方案--------------------------------------------------------
引用:
你注释的这个位置,显然已经是解析 int 失败的情况了,继续用 nextInt() 当然只能继续失败。。。

需要用 next() 来跳过当前待处理的输入信息。

+1
  相关解决方案