I'm trying to teach myself some java and this is my code, but these are the errors that i'm getting as soon as i make my first input telling the program which conversion mode to go into. Any help is appreciated
import java.util.Scanner;
public class TempConverter {
public static void cToF(){
double C=0, F=0, mode= 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter your temperature in Celsius.");
C = input.nextDouble();
input.close();
F = ((double)9/(double)5*C)+32;
System.out.println("The temperature you entered in Celsius:"+ C);
System.out.println("Converts to:"+ F + "in Fahrenheit");
System.out.println("entery any number to switch converters");
mode = input.nextDouble();
if (mode< 0 || mode >0){
ftoC();
}
}
public static void ftoC(){
double C=0, F=0, mode= 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter your temperature in Fahrenheit.");
F = input.nextDouble();
input.close();
C = (F-32)*((double)5/(double)9);
System.out.println("The temperature you entered in Fahrenheit:"+ F);
System.out.println("Converts to:"+ C + "in Celsius");
System.out.println("entery any number to switch converters");
mode = input.nextDouble();
if (mode< 0 || mode >0){
cToF();
}
}
public static void main(String[] args) {
int conv;
System.out.println("Enter 1 for F to C conversion");
System.out.println("Enter 2 for C to F conversion");
Scanner input = new Scanner(System.in);
conv = input.nextInt();
input.close();
if ( conv == 1) {
cToF();
}
else {
ftoC();
}
}
}
The problem is with your
input.close();
. WhenScanner
is opened forSystem.in
(keyboard entry stream), closing the Scanner also closes the stream itself.Technical details:
System.in
implementsCloseable
From
Scanner
docs:Suggested solution:
When using
Scanner
to capture keyboard input, open it once in the beginning and never close (or close at the very end of execution).