I'm a beginner in Java and I wanted to create a program where I can convert from celsius to fahrenheit but I need to be able to read and process data from a text file also. The text file has 5 lines of text each with different numeric values and when I run my program I'm only able to do a conversion for the first line of text. I know that I should be able to get my program to read all of the lines and do the calculations with a loop but I'm not sure how to do it. Any suggestions would be helpful. Here is my code so far:
import java.util.Scanner; import java.io.*; public class CToFConversion { char symbol = '\u00B0'; // this is the unicode "degree" symbol Scanner myScanner= new Scanner("tempdata.txt"); public void readFile(String file_name) { try{ File file = new File(file_name); Scanner myScanner= new Scanner(file); double celsius = myScanner.nextDouble(); double Fahrenheit = 9.0 / 5 * (celsius + 32); System.out.print(celsius + " Celsius is" + " Fahrenheit "); System.out.printf("%5.1f", Fahrenheit); while(myScanner.hasNextLine()){ System.out.println(myScanner.nextLine()); } }catch(Exception ex){ System.out.println(ex.getMessage()); System.exit(0); } } }
I also used another class to run this program, this is the code for that:
import java.io.*; public class CToFConversionLoop { public static void main(String[] args) throws IOException { CToFConversion conversion = new CToFConversion(); conversion.readFile("tempdata.txt");String file_name = "tempdata.txt"; } }
The text file has 5 lines:
0.0
33.3
100.0
-10.0
-273.0