o****i 发帖数: 1706 | 1 题目是这样的:
Write a code segment to prompt the user to input an integer between 0 and
100 (inclusive) and keep prompting the user until he does so. Verify both
the integer data type entered and the range.
我写的代码,有两个问题,一个是如果第一次输入的是小数,那会进入异常处理,可是
如果在catch的时候继续输入小数,那JAVA就处理不了了,然后就会出错。怎么才能改
进达到要求呢?谢谢!
import java.util.*;
public class Input {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
boolean finish=true;
int i=-1;
while(finish){
|
g*****g 发帖数: 34805 | 2 int a = 0;
while(true){
try{
a = scanner.nextInt();
if(! a in range) {
continue;
}else {
break;
}
} catch(Exception e){
continue;
}
}
【在 o****i 的大作中提到】 : 题目是这样的: : Write a code segment to prompt the user to input an integer between 0 and : 100 (inclusive) and keep prompting the user until he does so. Verify both : the integer data type entered and the range. : 我写的代码,有两个问题,一个是如果第一次输入的是小数,那会进入异常处理,可是 : 如果在catch的时候继续输入小数,那JAVA就处理不了了,然后就会出错。怎么才能改 : 进达到要求呢?谢谢! : import java.util.*; : public class Input { : public static void main(String[] args){
|
o****i 发帖数: 1706 | 3 我改了下,新的代码是
import java.util.*;
public class Input {
public static void main(String[] args){
Scanner input= new Scanner(System.in);
boolean finish=true;
int i=-1;
while(finish){
try{
System.out.println("Input an integer between 0 and 100:"
);
i=input.nextInt();
if(i>100||i<0){
System.out.println("Number input need to between 0
and 100");
}
|
h*****0 发帖数: 4889 | 4 因为你逻辑上不严谨。
输入错误了,你知道要finish = false;那输入正确时,你应该要记得让finish = true
;啊
【在 o****i 的大作中提到】 : 我改了下,新的代码是 : import java.util.*; : public class Input { : public static void main(String[] args){ : Scanner input= new Scanner(System.in); : boolean finish=true; : int i=-1; : while(finish){ : try{ : System.out.println("Input an integer between 0 and 100:"
|