I want to take input in the format: -prize 45
This is my code
static double prize_input(String list[]) throws IOException{
boolean flag=false;
double p=0;
while(true){
if(list.length!=2 || ( list[0].compareTo("-prize")!=0 ) ){
System.out.println("usage: -prize <Itemprize>");
flag=true;
}
else
{
try{
p=Double.parseDouble(list[1]);
flag=false;
}
catch(Exception e){
flag=true;
}
}
if(!flag)
return p;
else
list=br.readLine().split(" ");
}
}
When I input: -prize abc
where second argument is also a string it prompts me for another enter key from user instead of display the appropriate message. Please tell me what am I missing and how should I correct it.
当你正在接受(true)作为一个循环条件时,你的条件就是你的状态,并且你正在接受一个输入,其中循环将永远存在,并且缓冲读取器等待下一行被分割。
usage: -prize <Itemprize>
will be printed only if this condition will fail
if (list.length != 2 || (list[0].compareTo("-prize") != 0))
so only if
-prize
. Since for -price aaa
both conditions are fulfilled so user will not see this info, but flag
representing correctness of data will be set to false
while failed parsing second parameter, so in
else
list = br.readLine().split(" ");
program will be waiting for new data form
To improve user experience you should print usage info right before reading new data from user, so try moving line
System.out.println("usage: -prize <Itemprize>");
right before br.readLine()
else{
System.out.println("usage: -prize <Itemprize>");
list = br.readLine().split(" ");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.