对于学校,我正在编写一个程序,用户输入三个整数,程序找到这三个整数的乘积并将结果输出给用户。老师要求我使用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;
最佳答案
如果字符串不是有效的 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;
另外,询问家庭作业是一个令人不悦的问题,所以我将把你的第二个问题留给你来找出答案。
关于java - 如果未输入有效整数,如何让程序因错误而终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32893781/