Posts Tagged string

Java Tutorial 2 – User Input and Maths

First add this code:

Java is case sensitive so take care while typing.

How it works:

to get input from user we need to create a Scanner object that takes input.

We created Scanner object named “input”, you ca name it anything you like (eg. popcorn, bitch).

Now we created 3 doubles “x , y and ans”. Double is simply a variable that hold numeric value with decimal point.

We added System.out.println() lines to make it interactive.

in line “x= input.nextDouble();” we used input object and it’s “nextDouble()” method which returns a double and we stored it in the x.

We did same for variable y.

You can see suggestions while typing so you can find out other methods like nextInt() etc…

now understand this, System.out.println(“x+y =” + (x+y));

here “x+y =” is just a string but (x+y) is a value.

( confused..)

Any string in Java must be written in “…” and more than one strings can be printed together as “String 1” + “String 2”

and if u want to print string, int, double together simply saparet them with +.

for eg. If u want to print “your age is 10” and 10 is stored in variable x, you can do this by

System.out.println(“your age is ” + x ) and it will print the same.

And ya if you run it, it will run your previous class, but to run this class click shift+F6.

Thats it for this tutorial. Doubts are welcomed.

have a good 1, Peace.

, , , , , , , , ,

Leave a comment

Design a site like this with WordPress.com
Get started