我想给这个函数加个限制条件把那个输入的值限制在0-5之间,不知道要加在什么地方
==================================================================================
private static int getChoice() throws IOException {
do {
try {
stdErr.println("0 – Quit");
stdErr.println("1 – Display name");
stdErr.println("2 – Display address");
stdErr.println("3 – Display telephone");
stdErr.println("4 – Display email");
stdErr.println("5 – Display URL");
stdErr.print("Choice > ");
stdErr.flush(); return Integer.parseInt(stdIn.readLine()); } catch (NumberFormatException nfe) {
stdErr.println("Invalid number format");}
} while(true);
}
==================================================================================
private static int getChoice() throws IOException {
do {
try {
stdErr.println("0 – Quit");
stdErr.println("1 – Display name");
stdErr.println("2 – Display address");
stdErr.println("3 – Display telephone");
stdErr.println("4 – Display email");
stdErr.println("5 – Display URL");
stdErr.print("Choice > ");
stdErr.flush(); return Integer.parseInt(stdIn.readLine()); } catch (NumberFormatException nfe) {
stdErr.println("Invalid number format");}
} while(true);
}
int temp = Integer.parseInt(stdIn.readLine());
然后做判断
再return temp
参考:public static int getChoice() {
Scanner s = new Scanner(System.in);
int temp = Integer.parseInt(s.nextLine());
if(temp < 0 || temp > 5) {
System.out.println("Enter Again(0-5)!");
getChoice();
}
return temp;
}只是大概思路~~
int temp = Integer.parseInt(stdIn.readLine());
if (temp<0||temp>5)
{stdOut.println("Your input is out of range!");}
else
{return temp;}加了一个判断如上,我想问的是为什么我把那个temp变量直接换成Integer.parseInt(stdIn.readLine())运行出来就是错误的结果,定义一个temp就对了啊?
你直接return Integer.parseInt(stdIn.readLine())了
又没有做处理
我的回答到此完毕!!!