Again problem with understanding Java. When I asked previous question about Hello world in Java versus python, I received suggestion of taking the language as granted for a while till I don’t get hang of it. However, I cannot take that approach and is baffled by some weird things in Java versus python.
Here is the program which takes input from user and convert F to degree Celsius in python.
def main ():
fahr = input (" Enter the temperature in F: ")
cel = ( fahr - 32) * 5.0/9.0
print " the temperature in C is : " , cel
This is pretty straightforward without any quirky things going on inside.
The example to do the same thing in Java:
import java . util . Scanner ;
public class TempConv {
public static void main ( String [] args ) {
Double fahr ;
Double cel ;
Scanner in ;
in = new Scanner ( System . in );
System . out . println (" Enter the temperature in F: " );
fahr = in . nextDouble ();
cel = ( fahr - 32) * 5.0/9.0;
System . out . println (" The temperature in C is : " + cel );
System . exit (0);
}
}
What I thought should happen was: Scanner was Java class/instance of class/object to take user input and with
Scanner in
created a new object to take user input. It turns out to be we are just declaring in to be of Scanner type in Java (Correct me if I am wrong).
Now, if it was python, we would have just called the method of the newly created Scanner object that takes input from the user. OMG, what is this in Java? We create
new Scanner
object and pass System.in as a parameter and assign it to
in
again?
Can somebody please explain to me in pythonic terms, What is happening here and how and why it should differ from python so much?
Any creative suggestions are appreciated.
Your question is a little garbled, but here’s my attempt at an answer. In Java, just like in Python, you need to instantiate a class before you can call methods on it. In Python, you might do this:
In Java, the syntax is very similar:
And just like in Python, we can now call methods on it, such as:
This is just about identical to what the equivalent Python code would look like. It’s possible I’m not understanding the source of your confusion, so if this doesn’t help let me know and I’m happy to update things.