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:
public class Program2
public static void main(String args)
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))
output2 = "The product of the four digits is: "
+ ((posFourDigits % 10) * (posFourDigits / 10 % 10)
* (posFourDigits / 100 % 10) * (posFourDigits / 1000))
JOptionPane.showMessageDialog(null, output + output1 + output2,
"Program 2 (Artemus Watson)",
Re: The sum and product of a positive number between 1000 and 9999.
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 ;)