neighbordave 0 Newbie Poster

I am trying to get two numbers to overflow and print an error message stating this. it works for some numbers, but other numbers for example adding the numbers 1073741824 and 1073741825 results in a negative number -2147483647 which is clearly overflow. However, I cannot get these negative numbers to result in printing the error message because it is not greater than the MIN_VALUE (-2147483648).

Anyone have any ideas? I have been at this for about an hour and I cannot figure anything out.

public class Overflow {

	/**
	 * public static final int MIN_VALUE. A constant holding the minimum value an int can have, -2^31. 
	 */
	
	/**
	 * public static final int MAX_VALUE. A constant holding the maximum value an int can have, 2^31-1.  
	 */
	
	static final int MIN_VALUE = -2147483648;
	static final int MAX_VALUE = 2147483647;
	
	public static void main(String[] args) {
		
		//Scanner used to take in user input.
		Scanner keyboard = new Scanner (System.in);
		
		/**
		 * 3. Write a method that prompts for two integers. The method adds them and prints the sum to the screen. 
		 * If there is overflow, print a message to that effect.
		 */
		
		int input1; //User input #1
		int input2; //User input #2
		
		
		System.out.println("Case 3: Adding two user inputted integers and printing sum to screen. " +
				"\nIf there is overflow, there will be an overflow error message printed to the console. " +
				"\nPlease enter an integer: ");
		input1 = keyboard.nextInt();
		System.out.println("Please enter another integer: ");
		input2 = keyboard.nextInt();
		
		int sum = (input1 + input2); //Sum of user input #1 + user input #2
		
		if(sum < MIN_VALUE || sum > MAX_VALUE)
		{
			System.out.println("The sum of these two integers causes an overflow.\n");
		}
		else
		{
			System.out.println("The sum of the two integers is: " + sum + "\n");
		}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.