Translate

Showing posts with label reading input in java. Show all posts
Showing posts with label reading input in java. Show all posts

Monday, 18 August 2014

Program to read 2 values and display sum

class Sum
{
    public static void main(String args[])
    {
         int a, b;
         Console con = System.console();
         a = Integer.parseInt (con.readLine());
         b = Integer.parseInt (con.readLine());
         sum = a+b;
         System.out.print("Total is :- "+sum);         //we can also wrote con.printf("%d",sum);
    }
}

Reading an input and Creating object of a class

Object:-
Lets assume there is a class Matrix.
To create its object we will simply write
Matrix m = new Matrix();
OR
Matrix m;
m = new Matrix();

Reading an input:-
Here we will create object of console class to read a number, For this we will have to import java.io.*;

Console con = System.console();
String str;
str = con.readline();

Sample code:-
import java.io.*;
class ReadData
{
    public static void main(String args[])
    {
        Console con = System.console();
        String name, city;
        System.out.println("Enter your name");
        name = con.readLine();
        System.out.println("Where do you live?");
        city = con.readLine();
        System.out.println("Hello "+name+" from "+city+" You are welcome" );
    }
}

Total Pageviews