首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Eclipse开发 >

从键盘输入一个数,并判断这个数是或否在范围,若不在则重新输入。要如何实现,多谢大神帮忙

2013-04-02 
从键盘输入一个数,并判断这个数是或否在范围,若不在则重新输入。要怎么实现,谢谢大神帮忙我要从键盘输入一

从键盘输入一个数,并判断这个数是或否在范围,若不在则重新输入。要怎么实现,谢谢大神帮忙
我要从键盘输入一个数,并判断这个数是或否在1-5之间,若不在则重新输入,直到在1-5之间则停止,返回这个数  要怎么实现? 谢谢各路大神了。

下面是自己写的



import java.util.*;
public class Address {


public static int input(){
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
return n;
}

public static int reinput(int n){

while(true){
if(n<1||n>5){
System.out.println("请输入1-5之间的数!");
input();
}else
return n;

}
}

public static void main(String[] args){

reinput(input());    //这里的参数不知道怎么写 n好像不会更新 一直是第一次赋给的值
}
}


[解决办法]

package com.hqd.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputTest {

public void test() {
try {
System.out.print("请输入一个整数:");
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
int num;
num = Integer.parseInt(strin.readLine());
System.out.println(inputInt(num));
} catch (NumberFormatException 
[解决办法]
 IOException e) {
System.out.println("录入的数据不正确");
} finally {
test();
}
}

public String inputInt(int num) throws NumberFormatException, IOException {

if (num >= 1 && num <= 5) {
return "输入正确";
}
return "输入错误,请重新输入";

}

public static void main(String[] args) {
InputTest it = new InputTest();
it.test();
}

}

[解决办法]
其实楼上的写法还是不推荐的,这样的代码改起来挺麻烦的。。
在1楼上的基础上改了改,输入正确应该可以停了

try {
            System.out.print("请输入一个整数:");
            BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
            int num;
            num = Integer.parseInt(strin.readLine());
String str=inputInt(num);
            System.out.println(str);
        } catch (NumberFormatException 
[解决办法]
 IOException e) {
            System.out.println("录入的数据不正确");
        } finally {
if(!str.equels("输入正确""))
            test();
        }

热点排行