gpt4 book ai didi

java - 当用户输入 "N"时结束循环

转载 作者:行者123 更新时间:2023-12-02 13:36:39 25 4
gpt4 key购买 nike

当用户选择"is"时,它会循环并重新开始。当用户选择 N 时,它应该结束程序,但我不确定我在这里错过了什么。这是一个程序,可以在向程序提供斜率和 y 截距时告诉您 x 和 y 值。

Java 文件

        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();
}





}
}
}

最佳答案

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

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

关于java - 当用户输入 "N"时结束循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42960318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com