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.
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(" ");
}