对于学校,我正在制作一个程序,用户输入三个整数,程序找到这三个整数的乘积,并将结果输出给用户。老师要求我使用JOptionPane类。输入无效整数时,如何使程序以错误终止。而且,我如何在java窗口中输出答案?提前谢谢!
import javax.swing.JOptionPane;
public class ASTheProductofThreeGUI {
public static void main(String[] args) {
//initializes variable "answer" of type integer
//prompts the user to enter their first integer for the product of three
int value1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first"
+ " value as an integer"));
//prompts the user to enter their second integer
int value2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second"
+ " value as an integer"));
//prompts the user to enter their third integer
int value3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third"
+ " value as an integer"));
int answer = value1 * value2 * value3;
答案 0 :(得分:0)
如果字符串不是有效的Integer,Integer.parseInt将抛出异常。您应该处理NumberFormatException,然后调用System.exit。
import javax.swing.JOptionPane;
public class ASTheProductofThreeGUI {
public static void main(String[] args) {
//initializes variable "answer" of type integer
//prompts the user to enter their first integer for the product of three
try {
int value1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first"
+ " value as an integer"));
//prompts the user to enter their second integer
int value2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second"
+ " value as an integer"));
//prompts the user to enter their third integer
int value3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third"
+ " value as an integer"));
catch (NumberFormatException e){
e.printStackTrace("Invalid Integer entered.");
System.exit(0);
}
int answer = value1 * value2 * value3;
同时要求将家庭作业作为一个问题不以为然,所以我会留下你的第二个问题让你找出答案。
答案 1 :(得分:0)
public class JOptionPaneExample {
public static void main(String[] args){
try {
productOfThreeNumbers();
} catch (NumberFormatException e) {
e.printStackTrace();
showErrorDialog();
System.exit(0);
}
}
private static void productOfThreeNumbers() {
//initializes variable "answer" of type integer
//prompts the user to enter their first integer for the product of three
int value1 = Integer.parseInt(JOptionPane.showInputDialog("Enter your first"
+ " value as an integer"));
//prompts the user to enter their second integer
int value2 = Integer.parseInt(JOptionPane.showInputDialog("Enter your second"
+ " value as an integer"));
//prompts the user to enter their third integer
int value3 = Integer.parseInt(JOptionPane.showInputDialog("Enter your third"
+ " value as an integer"));
int answer = value1 * value2 * value3;
JOptionPane.showMessageDialog(null, String.format("%d * %d * %d = %d", value1, value2, value3, answer));
}
private static void showErrorDialog() {
//Put here code to show a friendly error message...
}}