Trying to read double data from the file that has different contents. For example if it is a double then the message should be “Double number is 23.5”. and if it is not double number the message should be “Sixty three is not a double number”. The file contents are
97.9
100.1
Three
Sixty three
77
12.4
3002.4
76
Cool
34.6
This is it
…………
The code i wrote opens the file and scans next line But does not seem to properly work.
class ReadDouble
{
Scanner scan = new Scanner(System.in);
try
{
File textFile = new File ("doubleData.txt");
Scanner scanFile = new Scanner (textFile);
String str = scan.nextLine();
while(scanFile.hasNextLine())
{
double num = Double.parseDouble(str);
if(str == num)
{
System.out.println("Double number is" + str);
}
}//end while
}//end try
catch (NumberFormatException nfe)
{
System.out.println(str + "Is not a Double number");
}
}
}//end class
First, you should call
String str = scan.nextLine();within the loop otherwise you only ever read the first line. Also, yourtry / catchblock should be wrapped arounddouble num = Double.parseDouble(str);within thewhileloop otherwise you will not make another call toscan.nextLine()after you encounter your first non-double.Finally, you shouldn’t do
if(str == num)as this will always be false. IfDouble.parseDouble(str)does not throw an exception, it contains the double found on that line.Here is a solution that reads from standard in:
Another option is to use
Scannerto see if the next element is adoubleif it is read it usingnextDouble()otherwise read usingnextLine().