Pages

Saturday, November 4, 2017

Java Program to Add Three Numbers (With Possible Runtime Exception)

1. Overview:


In this post, we will learn how to add three numbers in java with simple example program. We will explain step by step explanation.

In mathematics, the summation is calculated by using '+' [plus] operator. We will achieve the sum of three numbers using '+' operator in java.

Sum Of Three Numbers in Java

Formula:


sum = a + b + c;


Example Program:


package com.adeepdrive.sorting;

import java.util.Scanner;

// Java-W3schools
public class SumThreeNumbers {

 public static void main(String[] args) {

  int number1;
  int number2;
  int number3;

  Scanner scanner = new Scanner(System.in);
  System.out.println("Enter numner 1 : ");
  number1 = scanner.nextInt();

  System.out.println("Enter numner 2 : ");
  number2 = scanner.nextInt();

  System.out.println("Enter numner 3 : ");
  number3 = scanner.nextInt();

  int finalResult = number1 + number2 + number3;
  System.out.println("Final resut of sum of given three numbers is " + finalResult);

 }

}

Output:

Enter numner 1 : 10
Enter numner 2 : 20
Enter numner 3 : 30
Final result of the sum of given three numbers is 60

In the above program, We have used Scanner class to read the input from the user which is inputted through the keyboard. In older applications or before introducing the System.in, command-line arguments are used. Command lines arguments are well used to input to the scheduler jobs.

scanner.nextInt(): It is used to read integer value from the user. Only one value can be read at a time. If we want to read second value then again need to call the same method scanner.nextInt().

If user inputs other than integer value then will through runtime exception saying "InputMismatchException".


Exception in thread "main" java.util.InputMismatchException

 at java.util.Scanner.throwFor(Scanner.java:864)

 at java.util.Scanner.next(Scanner.java:1485)

 at java.util.Scanner.nextInt(Scanner.java:2117)

 at java.util.Scanner.nextInt(Scanner.java:2076)

 at com.adeepdrive.sorting.SumThreeNumbers.main(SumThreeNumbers.java:16)

In our example program, we have to call scanner.nextInt() method three times to read three values. After reading, we have to use the following expression for the summation of three numbers.

int finalResult = number1 + number2 + number3;

This expression is sufficient to add three numbers.

Another way to add three numbers without using '+' :

As of now, we did use the '+' operator. Now, we will see using the minus('-') operator produces the same result.


int finalResult = number1 - (-number2) - (-number3);

Please leave your questions in comment section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.