Java Exercises: Compute and print sum of two given integers.
Java Basic: Exercise-220 with Solution
Write a Java program to compute and print sum of two given integers (more than or equal to zero). If given integers or the sum have more than 80 digits, print "overflow".
Pictorial Presentation:
Sample Solution:
Java Code:
import java.*;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Input two integers:");
String s1 = new String();
String s2 = new String();
s1 = sc.nextLine();
s2 = sc.nextLine();
BigInteger b1 = new BigInteger(s1);
BigInteger b2 = new BigInteger(s2);
BigInteger result = new BigInteger("0");
result = result.add(b1);
result = result.add(b2);
String s3 = ""+result;
System.out.println("\nSum of the said two integers:");
if(s1.length()>80 || s2.length()>80 || s3.length()>80)
System.out.println("Overflow");
else
System.out.println(result);
}
}
Sample Output:
Input two integers: 25 46 Sum of the said two integers: 71
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if a point (x, y) is in a triangle or not. There is a triangle formed by three points.
Next: Write a Java program that accepts six numbers as input and sorts them in descending order.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework