Shniper Shniper - 3 months ago 10
Java Question

Method not working, no compiler errors

I'm sorry for this question because I know it's really simple, but I'm used to python and js, so java is very new to me and I haven't found anything telling me why this isn't working.

import java.util.Scanner;
public class HelloWorld{

public static void main(String []args){

}

public static double changeToFahrenheit(){

Scanner reader = new Scanner(System.in);
System.out.println("Enter a number between 0-20: ");
double celsius = reader.nextInt();
double fahrenheit = (9/5) * celsius +32;

System.out.println(fahrenheit);
return fahrenheit;
}
}


When I run this I get
"sh-4.3$ java -Xmx128M -Xms16M HelloWorld"


I'm using the codinggrounds Java compiler and executer, I would like for it to ask for a number and then convert it to fahrenheit upon user input

Answer

You have to actually call changeToFahrenheit from your main method, so your code is:

import java.util.Scanner;
public class HelloWorld{

     public static void main(String []args){
          changeToFahrenheit();
     }

    public static double changeToFahrenheit(){

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number between 0-20: ");
        double celsius = reader.nextInt();
        double fahrenheit = (9/5) * celsius +32;

        System.out.println(fahrenheit);
        return fahrenheit;
    }
}

To use a function, you must call a function (This is like the equivalent of the Main function in C#). By the way, you cannot do 9/5, since integer division will result in an integer, 1. Try 9.0/5.0 for the computation.