当前位置: 首页 > 知识库问答 >
问题:

我很难跳到一个循环的正确部分

司空鸿禧
2023-03-14

我要做的是让用户输入一个分子和一个分母,并显示商。我正在使用一个方法,使用Integer.Parseint和try catch来检查并查看该数字是否有效。问题是,如果try catch捕获异常并显示错误,它将继续到代码的下一部分,而不是跳回到循环的开始。

public static void main(String[] args) {
        String numerator = "";
        String denominator = "";
        String message = "";
        int num = 0;
        int den = 0;
        int quo = 0;
        int yesNo = 0;
        do
        {
            // Displays a JOptionPane asking the user to input a numerator.
            numerator = JOptionPane.showInputDialog(null, "Please enter a numerator.", "Enter a Numerator",JOptionPane.QUESTION_MESSAGE);
            if(numerator == null)// This breaks the loop if  the user clicks the "cancel" button.
                break;
            num = IsValid(numerator); // Calls the IsValid method, passing it the String entered by the user to validate if it is a proper integer.
            denominator = JOptionPane.showInputDialog(null, "Please enter a denominator.", "Enter a Denominator",JOptionPane.QUESTION_MESSAGE);
            if(denominator == null) // same as above but for the denominator
                break;
            den = IsValid(denominator);
            /*if(den != 0 && num<den) 
            { // This section is unrelated to my problem
                quo = num/den;
                message = "Numerator: " + num + "\n" +
                            "Denominator: " + den + "\n" +
                            "Quotient: ";
                JOptionPane.showMessageDialog(null, message,"Calculation",JOptionPane.INFORMATION_MESSAGE);
            }*/
            yesNo = JOptionPane.showConfirmDialog(null,"Would you like to make another calculation?","Continue?",JOptionPane.YES_NO_OPTION);
        }while(yesNo == JOptionPane.YES_OPTION);
    }
    public static int IsValid(String input)
    {
        int num = 0; // This method is passed the String that the JOptionPane receives and using Integer.parseInt to make sure it's an integer, and assigns it to int "num".
        try{num = Integer.parseInt(input);}
        catch(NumberFormatException ex)
        {
            JOptionPane.showMessageDialog(null, "Error: Invalid number. Please enter a valid number.","Invalid Input",JOptionPane.WARNING_MESSAGE);
        }
        return num;
        // My main issue is that it continues with the code instead of jumping back to the JOptionPane to ask the user for input a second time.
    }

基本上,我想调用IsValid(分子)并将其赋给int“num”,如果IsValid的catch语句被执行,则跳回到do循环的开头,以便它再次显示JOptionPane。如果针对分母执行catch语句,则跳回到该分母,而不是最开始。我不能将JOptionPane放入方法中,因为方法将无法判断我是发送给它分子还是分母。我对java还很陌生,我确信有更简单的方法来实现这一点,所以我们非常感谢任何帮助。谢谢!

共有1个答案

辛龙野
2023-03-14

如果输入无效,对isvalid的调用将中断程序。最自然的方法是让它抛出一个异常。然后程序捕获异常并退出。

package so20190423;

import java.awt.HeadlessException;

import javax.swing.JOptionPane;

public class Snippet {
    public static void main(String[] args) {
            String numerator = "";
            String denominator = "";
            String message = "";
            int num = 0;
            int den = 0;
            int quo = 0;
            int yesNo = 0;
            try {
                do
                {
                    // Displays a JOptionPane asking the user to input a numerator.
                    numerator = JOptionPane.showInputDialog(null, "Please enter a numerator.", "Enter a Numerator",JOptionPane.QUESTION_MESSAGE);
                    if(numerator == null)// This breaks the loop if  the user clicks the "cancel" button.
                        break;
                    num = IsValid(numerator); // Calls the IsValid method, passing it the String entered by the user to validate if it is a proper integer.
                    denominator = JOptionPane.showInputDialog(null, "Please enter a denominator.", "Enter a Denominator",JOptionPane.QUESTION_MESSAGE);
                    if(denominator == null) // same as above but for the denominator
                        break;
                    den = IsValid(denominator);
                    /*if(den != 0 && num<den) 
                    { // This section is unrelated to my problem
                        quo = num/den;
                        message = "Numerator: " + num + "\n" +
                                    "Denominator: " + den + "\n" +
                                    "Quotient: ";
                        JOptionPane.showMessageDialog(null, message,"Calculation",JOptionPane.INFORMATION_MESSAGE);
                    }*/
                    yesNo = JOptionPane.showConfirmDialog(null,"Would you like to make another calculation?","Continue?",JOptionPane.YES_NO_OPTION);
                }while(yesNo == JOptionPane.YES_OPTION);
            }
            catch(NumberFormatException ex)
            {
                JOptionPane.showMessageDialog(null, "Error: Invalid number. Please enter a valid number.","Invalid Input",JOptionPane.WARNING_MESSAGE);
            }
        }
        public static int IsValid(String input) throws NumberFormatException
        {
            int num = 0; // This method is passed the String that the JOptionPane receives and using Integer.parseInt to make sure it's an integer, and assigns it to int "num".
            num = Integer.parseInt(input);
            return num;
            // My main issue is that it continues with the code instead of jumping back to the JOptionPane to ask the user for input a second time.
        }
}

您甚至可以将try/catch限制在while循环中,以便在输入失败后恢复并重试!

package so20190423;

import java.awt.HeadlessException;

import javax.swing.JOptionPane;

public class Snippet {
    public static void main(String[] args) {
            String numerator = "";
            String denominator = "";
            String message = "";
            int num = 0;
            int den = 0;
            int quo = 0;
            int yesNo = 0;
                do
                {
                    try {
                    // Displays a JOptionPane asking the user to input a numerator.
                    numerator = JOptionPane.showInputDialog(null, "Please enter a numerator.", "Enter a Numerator",JOptionPane.QUESTION_MESSAGE);
                    if(numerator == null)// This breaks the loop if  the user clicks the "cancel" button.
                        break;
                    num = IsValid(numerator); // Calls the IsValid method, passing it the String entered by the user to validate if it is a proper integer.
                    denominator = JOptionPane.showInputDialog(null, "Please enter a denominator.", "Enter a Denominator",JOptionPane.QUESTION_MESSAGE);
                    if(denominator == null) // same as above but for the denominator
                        break;
                    den = IsValid(denominator);
                    /*if(den != 0 && num<den) 
                    { // This section is unrelated to my problem
                        quo = num/den;
                        message = "Numerator: " + num + "\n" +
                                    "Denominator: " + den + "\n" +
                                    "Quotient: ";
                        JOptionPane.showMessageDialog(null, message,"Calculation",JOptionPane.INFORMATION_MESSAGE);
                    }*/
                    yesNo = JOptionPane.showConfirmDialog(null,"Would you like to make another calculation?","Continue?",JOptionPane.YES_NO_OPTION);
                }
                catch(NumberFormatException ex)
                {
                    JOptionPane.showMessageDialog(null, "Error: Invalid number. Please enter a valid number.","Invalid Input",JOptionPane.WARNING_MESSAGE);
                }
                }while(yesNo == JOptionPane.YES_OPTION);
        }
        public static int IsValid(String input) throws NumberFormatException
        {
            int num = 0; // This method is passed the String that the JOptionPane receives and using Integer.parseInt to make sure it's an integer, and assigns it to int "num".
            num = Integer.parseInt(input);
            return num;
            // My main issue is that it continues with the code instead of jumping back to the JOptionPane to ask the user for input a second time.
        }
}


最后一个变体,如果你想重试每个输入直到它有效(或者被用户取消):

package so20190423;

import javax.swing.JOptionPane;

public class Snippet {
    public static void main(String[] args) {
        String numerator = "";
        String denominator = "";
        String message = "";
        int num = 0;
        int den = 0;
        int quo = 0;
        int yesNo = 0;
        do {
            boolean userCancelled = false;
            boolean numeratorIsOk = false;
            do {
                try {
                    numerator = JOptionPane.showInputDialog(null, "Please enter a numerator.", "Enter a Numerator",
                            JOptionPane.QUESTION_MESSAGE);
                    if (numerator == null) {
                        userCancelled = true;
                    } else {
                        num = IsValid(numerator);
                        numeratorIsOk = true;
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "Error: Invalid number. Please enter a valid number.",
                            "Invalid Input", JOptionPane.WARNING_MESSAGE);
                }
            } while (!numeratorIsOk && !userCancelled);
            if (userCancelled) {
                break;
            }

            boolean denominatorIsOk = false;
            do {
                try {
                    denominator = JOptionPane.showInputDialog(null, "Please enter a denominator.",
                            "Enter a Denominator", JOptionPane.QUESTION_MESSAGE);
                    if (denominator == null) {
                        userCancelled = true;
                    } else {
                        den = IsValid(denominator);
                        denominatorIsOk = true;
                    }
                    /*
                     * if(den != 0 && num<den) { // This section is unrelated to my problem quo =
                     * num/den; message = "Numerator: " + num + "\n" + "Denominator: " + den + "\n"
                     * + "Quotient: "; JOptionPane.showMessageDialog(null,
                     * message,"Calculation",JOptionPane.INFORMATION_MESSAGE); }
                     */
                    yesNo = JOptionPane.showConfirmDialog(null, "Would you like to make another calculation?",
                            "Continue?", JOptionPane.YES_NO_OPTION);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "Error: Invalid number. Please enter a valid number.",
                            "Invalid Input", JOptionPane.WARNING_MESSAGE);
                }

            } while (!denominatorIsOk && !userCancelled);
            if (userCancelled) {
                break;
            }
        } while (yesNo == JOptionPane.YES_OPTION);

    }

    public static int IsValid(String input) throws NumberFormatException {
        int num = 0; // This method is passed the String that the JOptionPane receives and using
                        // Integer.parseInt to make sure it's an integer, and assigns it to int "num".
        num = Integer.parseInt(input);
        return num;
        // My main issue is that it continues with the code instead of jumping back to
        // the JOptionPane to ask the user for input a second time.
    }
}

 类似资料:
  • 我的程序中有两个while循环。第一个是针对游戏菜单的,第二个是针对实际游戏的。如果“Gameover-Event”发生,我想返回菜单。我不知道该怎么做。

  • 这是我的for循环。。。jGRASP说在我的for循环中出现了一个问题,我看不出这个问题,希望能得到一些帮助来修复我的代码。。。 公共类DirectoryLookup{public static void main(String[]args)引发IOException{

  • 我现在正在学习css。我在做一个作业,我必须遵循一组指令,并添加css规则,使页面看起来有一定的方式,并使我理解不同的规则。我完全按照说明去做,但是我的页面看起来和作业中的页面有很大的不同。说明如下。 在html文档正文头部的样式标记之间包含以下两个CSS规则{font-family:Calibri,Sans-serif;background-color:#CAFeb8;}header{borde

  • 如果为正值,则使用指针移动 次 如果为负,则使用指针移动 次 如果为0,则根本不移动。 我需要编写一个方法,该方法接收指向列表头部的指针作为参数,如果有一个在头部节点开始和结束的跳转路径,则返回。 一个示例列表: 这不是家庭作业(我正在做不同的练习,以便为考试做准备)

  • 我有3个div。当我点击特定的按钮时,每个人都会有类活动。它们的每个div都有一个状态变量,每当它是真的时,我都会向连接到它的div添加class Name='active': 当我点击按钮时,状态改变,但是div没有激活类 当我将函数更改为此时,它会工作: ================================================ =====================