java - end loop when user types "N"

时间:2017-03-22 18:51:38

标签: java

When the user selects yes, it loops and starts again. When the user selects N, it should end the program but I am not sure what I am missing here. This is a program to tell you the x and y values when giving the slope and y-intercept to the program.

Java file

        int slope;
        int yintercept;
        String newEquation;
        boolean play = true; 


        System.out.print("Enter the slope: ");
        slope = input.nextInt();

        System.out.print("Enter y-intercept: ");
        yintercept = input.nextInt();

        System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);

        System.out.print("\nWould you like to create a new equation... Y or N? ");
        newEquation = input.next();


            while (play)
            {
                if (newEquation.equals("Y"))
                {
                    System.out.print("Enter the slope: ");
                    slope = input.nextInt();

                    System.out.print("Enter y-intercept: ");
                    yintercept = input.nextInt();

                    System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);

                    System.out.print("\nWould you like to create a new equation... Y or N? ");
                    newEquation = input.next();
                }
                if (newEquation.equals("N")){
                    play =false; 

                }
                else{
                    System.out.print("Enter the slope: ");
                    slope = input.nextInt();

                    System.out.print("Enter y-intercept: ");
                    yintercept = input.nextInt();

                    System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);

                    System.out.print("\nWould you like to create a new equation... Y or N? ");
                    newEquation = input.next();
                }





            }
    }   
}

2 个答案:

答案 0 :(得分:1)

为什么在 if(newEquation.equals(“Y”)) else 部分中使用相同的代码?如果您希望用户只输入“Y”或“N”,那么您可以将其他内容放在fron中,如下所示: else if(newEquation.equals("N")) 并删除其他部分。

因为你编写它的方式,它测试输入是否为“Y”,然后在同一循环迭代中第二次测试输入是否为“N”,这意味着你的程序采用斜率当它通过循环时,信息两次,因为else仅指“N”。

答案 1 :(得分:0)

尝试一个do-while构造,以及一个equalsIgnoreCase(制作" y"和" Y"两者都针对" Y" )。

int slope;
int yintercept;
String newEquation;
boolean play = true; 


do
{
    System.out.print("Enter the slope: ");
    slope = input.nextInt();

    System.out.print("Enter y-intercept: ");
    yintercept = input.nextInt();

    System.out.printf("The equation of the line is: y = %dx + %d", slope, yintercept);

    System.out.print("\nWould you like to create a new equation... Y or N? ");
    newEquation = input.next();
} while newEquation.equalsIgnoreCase("Y")

(我只剪了你的线,但没有编译和测试。如果我错过了什么,我道歉。)

do-while测试用户是否在第一轮之后键入了Y / y。请注意,用户不必键入N / n,而是可以键入q,以便循环终止。