java中Scanner问题,循环输入出错
importjava.util.*;//importjava.lang.Math;classNumberTooBigextendsException{intdivisor...
import java.util.*;
//import java.lang.Math;
class NumberTooBig extends Exception{
int divisor;
public NumberTooBig(String msg, int divisor){
super(msg);
this.divisor=divisor;
}
public int getDivisor(){
return divisor;
}
}
class Operation{
int userAnswer;
void getAnswer() {
Scanner keyboard=new Scanner(System.in);
for(;;){
try{
userAnswer= Integer.parseInt(keyboard.nextLine().trim());
break;
}
catch(NumberFormatException nfe){
System.out.print("输入数据类型错误!你必须输入数值数据!\n");
}
}
keyboard.close();
};
}
public class ScannerTest{
public static void main(String args[]){
Operation i=new Operation();
Scanner keyboard=new Scanner(System.in);
for(;;){
i.getAnswer();
try{
if(i.userAnswer>50)
throw new NumberTooBig("数值太大\n",i.userAnswer);
break;
}
catch(NumberTooBig n){
System.out.print(n.getMessage());
}
}
System.out.println(i.userAnswer);
}
}
如果我输入100,结果出现
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Operation.getAnswer(ScannerTest.java:21)
at ScannerTest.main(ScannerTest.java:36) 展开
//import java.lang.Math;
class NumberTooBig extends Exception{
int divisor;
public NumberTooBig(String msg, int divisor){
super(msg);
this.divisor=divisor;
}
public int getDivisor(){
return divisor;
}
}
class Operation{
int userAnswer;
void getAnswer() {
Scanner keyboard=new Scanner(System.in);
for(;;){
try{
userAnswer= Integer.parseInt(keyboard.nextLine().trim());
break;
}
catch(NumberFormatException nfe){
System.out.print("输入数据类型错误!你必须输入数值数据!\n");
}
}
keyboard.close();
};
}
public class ScannerTest{
public static void main(String args[]){
Operation i=new Operation();
Scanner keyboard=new Scanner(System.in);
for(;;){
i.getAnswer();
try{
if(i.userAnswer>50)
throw new NumberTooBig("数值太大\n",i.userAnswer);
break;
}
catch(NumberTooBig n){
System.out.print(n.getMessage());
}
}
System.out.println(i.userAnswer);
}
}
如果我输入100,结果出现
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Operation.getAnswer(ScannerTest.java:21)
at ScannerTest.main(ScannerTest.java:36) 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询