I am new at Java so thank you for helping!
public static int convert (String value) {
int temp_convert = 0;
// Setting up new Scanner to read the User-input string
Scanner token = new Scanner(value);
// Take out the word "CONVERT"
String fnc = token.next();
// Get the temperature that needs to be converted
int temp = token.nextInt();
// Current unit of temperature
String type = token.next().toLowerCase();
if (type.equals("f")) {
temp_convert = (int) Math.round((temp - 32)/1.8);
System.out.println(temp_convert + "C");
} else if (type.equals("c")) {
temp_convert = (int) Math.round(1.8 * temp + 32);
System.out.println(temp_convert + "F");
}
return temp_convert;
}
I am trying to get the print result from this method into an output file using PrintStream. I need whatever is lines printed in this method to be print out into the output file. How can I do this? This is the code I have so far but it doesn't produce anything in the .txt file yet.
public static void readFile (Scanner console, String file_input) throws FileNotFoundException {
// Setting up new Scanner to scan the file
Scanner input = new Scanner (file_input);
// Prompt user for output file's name
System.out.print("Output file name: ");
String name_output = console.next();
PrintStream file_output = new PrintStream(new File(name_output));
System.out.println("YazLang program interpreted and output to .txt file!");
System.out.println();
while (input.hasNext()) {
String value = input.nextLine().toLowerCase();
if (value.startsWith("convert")) {
int concert_temp = convert(value);
file_output.println(concert_temp);
} else if (value.startsWith("range")) {
range(value);
} else if (value.startsWith("repeat")) {
repeat(value);
}
}
}
Why don't you change signature of
convertmethod to returnint?And then write result to file in
readFilemethod like this: