-1

Here is the code I'm messing around with:

import java.util.*; public class Work {

public static void main(String[] args){
    System.out.println("Type 1 to convert from Farenheit to Celsius. Type 2 to convert from Farenheit to Kelvin.");
    Scanner sc = new Scanner(System.in);
    double x = sc.nextDouble();
    while ((x != 1) && (x != 2)){
    System.out.println("Please enter a value of either 1 or 2");
    x = sc.nextDouble();
    }

    if (x == 1){
        System.out.println("Enter the degrees in F and it will be converted to C:");
        double y = sc.nextDouble();
        double ans = convertoC(y);
        System.out.println(ans + " C");
    } else if (x == 2){
        System.out.println("Enter the degrees in F and it will be converted to K:");
        double v = sc.nextDouble();
        double ans = convertoK(v);
        System.out.println(ans + " K");
    } 
}


public static double convertoK(double x){
    return ((x + 459.67) * (5.0/9.0));
}

public static double convertoC(double x){
    return ((x - 32.0) * (5.0/9.0));
}

}

Eclipse tells me there is a resource leak for the Scanner. How can I correct this? Also, is there a more efficient way to receive inputs then this? I feel like my implementation is very blocky and re-uses the same code over an over. Also, would I use a try/catch to allow a user to re-enter another input if they don't input a number (as it is, an exception simply gets thrown).

Thanks!

Laugh7
  • 167
  • 2
  • 2
  • 16
  • 2
    Please share relevant parts of the code here, don't link us to places. – Maroun Jan 26 '16 at 08:02
  • 3
    Don't create more than one `Scanner`. Create one, and only one, then use it wherever needed. Lifetime is entire `main()` method, so in the end, one resource may be detected as being leaked, which is not really true, so just ignore that, because you don't want to close the underlying `System.in`. – Andreas Jan 26 '16 at 08:05
  • I have updated the code from a link. Sorry! – Laugh7 Jan 26 '16 at 08:07
  • This question & answer could be relevant: http://stackoverflow.com/a/14143047/638028 – Klitos Kyriacou Jan 26 '16 at 09:37

1 Answers1

2

You need to close() the scanner so that any resources held by it can be released. Ideally, this is done in a finally block so that you are sure that you will always release the resources accumulated by the scanner.

Thus, you would need to declare the scanner: Scanner sc = null, then, wrap the remainder of your method within a try-catch block. Lastly, add a finally block wherein you close the scanner (sc) provided that it is not null.

As per @Kevin Esche comment, you can also use the try-with-resources, which is similar to C#'s using directive.

You are also declaring multiple scanners on the same item within the same scope. The scanner you declare at the top should be enough, sx and sy are unneeded.

npinti
  • 51,780
  • 5
  • 72
  • 96