The sum and product of a positive number between 1000 and 9999.

I wrote a program that asks the user for a number and displays the original number, the sum of the digits and the product of the digits. I need to add an ERROR message if the number entered is not positive or between 1000 and 9999. I also need it to display "Zero" if the product of the four digits is 0. I am just trying to figure out the easiest way of accomplishing this task. This is what I have so far:

import javax.swing.JOptionPane;

public class Program2

{

public static void main(String[] args)

{

String userInput;

int posFourDigits;

String output, output1, output2;

userInput = JOptionPane

.showInputDialog("Enter a positive four digit number between 1000 and 9999: ");

posFourDigits = Integer.parseInt(userInput);

output = "The original number is: " + (posFourDigits) + "\n";

output1 = "The sum of the four digits is: "

+ ((posFourDigits % 10) + (posFourDigits / 10 % 10)

+ (posFourDigits / 100 % 10) + (posFourDigits / 1000))

+ "\n";

output2 = "The product of the four digits is: "

+ ((posFourDigits % 10) * (posFourDigits / 10 % 10)

* (posFourDigits / 100 % 10) * (posFourDigits / 1000))

+ "\n";

JOptionPane.showMessageDialog(null, output + output1 + output2,

"Program 2 (Artemus Watson)",

JOptionPane.PLAIN_MESSAGE);

System.exit(0);

}

}

Re: The sum and product of a positive number between 1000 and 9999.

Hi metaleddie13,

Your issues sound like general exception - handling issues. Have you considered using the try...catch statement to determine if the number is not positive? You can also use this to determine if the number is between 1000 and 9999.

Remember, try...catch statements should always go from most specific to most general. This is because if you catch the most general exception first, it will account for all of the exceptions, making it harder to understand what the specific error is. This will also enable you to display a 0.

You should be able to code the user input request in the try block and the exceptions afterwards.

Good luck and let me know if you solve it ;)

~switch~