从键盘输入一个数,并判断这个数是或否在范围,若不在则重新输入。要怎么实现,谢谢大神帮忙
我要从键盘输入一个数,并判断这个数是或否在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();
}
}
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();
}