Encountering some bugs regarding the Scanner and an unknown source in my code. No idea how to fix it

旧城冷巷雨未停 提交于 2019-12-25 05:33:37

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/27833107/encountering-some-bugs-regarding-the-scanner-and-an-unknown-source-in-my-code-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!