gpt4 book ai didi

java - 我怎样才能退出这个 while 循环并使其在有人输入 "? quit"时程序将终止

转载 作者:行者123 更新时间:2023-11-30 03:17:33 26 4
gpt4 key购买 nike

import java.util.Scanner;
public class RectAngleObj {
public static void main(String args[]) {
String sPeri = "perimeter";
String sArea = "area";
String sQues = "?";
String sQuit = "quit";
String f;
String g;
String h;
String j;

Scanner sc = new Scanner(System.in);

while(sc.hasNext()){
f = sc.next(); // assigns the first standard input to f (can either be ? or quit)
g = sc.next(); // assigns the second word from standard input to g (can either be perimeter or area)
if(f.equals(sQues)) { // if first word is equal to "?" then the if statements continue
if (g.equals(sPeri)) { // if the second word is equal to "perimeter" print out result
double a = sc.nextDouble(), // assigns next four doubles to a, b, c, d
b = sc.nextDouble(),
c = sc.nextDouble(),
d = sc.nextDouble();
RectAngle3 r = new RectAngle3(a, b, c, d); // creates an object of RectAngle3 with dimensions of a, b, c, d
System.out.println("Perimeter of (" + r.rectNums() + "): " + r.rectPeri());
} if (g.equals(sArea)) { // if the second word is equal to "area" print out result
double a = sc.nextDouble(), // assigns next four doubles to a, b, c, d
b = sc.nextDouble(),
c = sc.nextDouble(),
d = sc.nextDouble();
RectAngle3 r = new RectAngle3(a, b, c, d); // creates an object of RectAngle3 with dimensions of a, b, c, d
System.out.println("Area of (" + r.rectNums() + "): " + r.rectArea());
}
}
}
}
}

我希望 while 循环自然结束,而不使用 System.exit(0);或打破;请帮忙!

理想情况下,如果有人输入“? quit”,程序就会结束。

我没有收到任何错误,循环会永远持续下去...不知道此时要做什么。

最佳答案

您需要更改循环,使其具有退出条件,而不是使用 while (sc.hasNext()并在“问题” block 中添加一个条件来检查用户是否输入了 sQuit ,例如

boolean hasQuit = false;
do {
f = sc.next(); // assigns the first standard input to f (can either be ? or quit)
g = sc.next(); // assigns the second word from standard input to g (can either be perimeter or area)
if (f.equals(sQues)) { // if first word is equal to "?" then the if statements continue
if (g.equals(sQuit)) {
hasQuit = true;
} else if (g.equals(sPeri)) { // if the second word is equal to "perimeter" print out result
//...
} else if (g.equals(sArea)) { // if the second word is equal to "area" print out result
//...
}
}
} while (!hasQuit);

关于java - 我怎样才能退出这个 while 循环并使其在有人输入 "? quit"时程序将终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216402/

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