java-当用户类型为“时结束循环”;";
当用户选择yes时,它将循环并再次启动。当用户选择N时,它应该结束程序,但我不确定这里缺少什么。这是一个程序,用于在向程序提供斜率和y截距时告诉您x和y值 Java文件java-当用户类型为“时结束循环”;";,java,Java,当用户选择yes时,它将循环并再次启动。当用户选择N时,它应该结束程序,但我不确定这里缺少什么。这是一个程序,用于在向程序提供斜率和y截距时告诉您x和y值 Java文件 int slope; int yintercept; String newEquation; boolean play = true; System.out.print("Enter the slope: "); slope =
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();
}
}
}
}
尝试do-while构造,以及
equalsIgnoreCase
(使“y”和“y”都与“y”进行测试)
(我只是剪贴了你的台词,但没有编译和测试。如果我遗漏了什么,我深表歉意。)
do while测试用户在第一轮之后是否键入了Y/Y。请注意,用户不必键入N/N,而是可以键入,例如,q,以便循环终止 为什么在if(newEquation.equals(“Y”)和else部分有相同的代码?如果您希望用户只输入“Y”或“N”,那么您可以在fron中输入else,如下所示:
else if(newEquation.equals(“N”))
并删除其他部分
因为您编写它的方式,它测试输入是否为“Y”,然后在同一个循环迭代中第二次它将测试输入是否为“N”,这意味着您的程序在通过循环时将斜率信息取两次,因为else仅指“N” 它对我有用。您是否键入了“n”而不是“n”?通过使用Java的do-while构造,您可以大大简化代码。哦,哇,我有多蠢“当用户选择是时,它会循环并再次启动”我对此表示怀疑。你从来没有检查过“是的”@FredK有足够的重复,如果他们输入“是的”,它实际上会重复。它只是进入“else”而不是第一个“if”。
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")