Hi, I am facing a problem in the following code as what should be the while condition I should use in order to get the loop keep running until i get the desired double value and come out of the loop once condition is met.
System.out.println(" You have selected Celsius");
temp_name= "Celsius";
do
{
Scanner temp_ip= new Scanner(System.in);
System.out.println("Please enter the temperature in celsius");
if (temp_ip.hasNextDouble())
{
temp_usr= temp_ip.nextDouble();
}
else
{
System.out.println("Invalid Input. Try Again!!!");
}
}
while();
I think it should help you jasmeet
package myFunc;
import java.util.Scanner;
public class ScannerDemo { static double n=0.0; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in);
while(!isDouble(sc.nextLine())){
System.out.println("Invalid Input. Try Again!!!");
}
}
static boolean isDouble(String str) {
try {
n=Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
I think it should help you jasmeet
package myFunc;
import java.util.Scanner;
public class ScannerDemo { static double n=0.0; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in);
while(!isDouble(sc.nextLine())){
System.out.println("Invalid Input. Try Again!!!");
}
}
static boolean isDouble(String str) {
try {
n=Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
hello, thanks for the answers. I know that it could be done using try n catch concept but I don't want to use this and want to execute without initially just to have a good hold on basics.
Please post your answer without using try n catch.
Thanks again! jasmeet