Tutorial - Java - Add two numbers


Coding Friends Tutorial Index - > Java

Author Ian - Tutorial Posts = 62
This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the InputStreamReader to convert the System.in (console) into a stream, which into converted with a BufferedReader to get the whole line and not just one character/number.

The code
---
// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;

class addtwonumbers
{
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
              
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + (val1 + val2));
       }
}
---
save that as addtwonumbers.java, because of course java is very picky about the class name to the java file, because Java creates a class of the same name as the class which in-turn is what the java virtual machine uses to execute.

Once compiled (javac addtwonumbers.java) and executed (java addtwonumbers) the output will be
Enter first number : 30
Enter second number : 23
Answer = 53
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search