Encountering some bugs regarding the Scanner and a

2019-09-05 22:09发布

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

Errors

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();
        }
    }
}

1条回答
趁早两清
2楼-- · 2019-09-05 22:48

The problem is with your input.close();. When Scanner is opened for System.in (keyboard entry stream), closing the Scanner also closes the stream itself.

Technical details:

System.in implements Closeable

From Scanner docs:

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

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).

查看更多
登录 后发表回答