无法跳出 while 循环。
Unable to break out of a while loop.
如果用户输入特定输入,我必须跳出循环。但是我无法使用 if 循环跳出 while 循环来做到这一点。我也尝试在 while 循环中使用相同的条件,但这也不起作用。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String quit;
Scanner c = new Scanner(System.in);
while (true) {
leapOrNot y = new leapOrNot();
System.out.println("press x to stop or any other letter to continue");
quit = c.next();
if (quit == "x" || quit == "X") {
break;
}
}
}
}
class leapOrNot {
final String isLeap = " is a leap year.";
final String notLeap = " is not a leap year.";
int year;
public leapOrNot() {
Scanner a = new Scanner(System.in);
System.out.println("Enter a year after 1581: ");
year = a.nextInt();
/* if (a.hasNextInt() == false) {
System.out.println("Enter a 4 digit integer: ");
year = a.nextInt();
}
couldn't make this condition work either
*/
while (year < 1582) {
System.out.println("The year must be after 1581. Enter a year after 1581: ");
year = a.nextInt();
continue;
}
if (year % 4 == 0) {
if(year % 400 == 0 && year % 100 == 0) {
System.out.println(year + isLeap);
}
if (year % 100 == 0) {
System.out.println(year + notLeap);
}
else {
System.out.println(year + isLeap);
}
}
else {
System.out.println(year + notLeap);
}
}
}
您应该使用 String.equals()
。替换为这两个中的任何一个
if (quit.charAt(0) == 'x' || quit.charAt(0) == 'X')
if (quit.equals("x") || quit.equals("X"))
以上任何一个都可以正常工作。
或者只使用 if(quit.equalsIgnoreCase("x"))
如果用户输入特定输入,我必须跳出循环。但是我无法使用 if 循环跳出 while 循环来做到这一点。我也尝试在 while 循环中使用相同的条件,但这也不起作用。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String quit;
Scanner c = new Scanner(System.in);
while (true) {
leapOrNot y = new leapOrNot();
System.out.println("press x to stop or any other letter to continue");
quit = c.next();
if (quit == "x" || quit == "X") {
break;
}
}
}
}
class leapOrNot {
final String isLeap = " is a leap year.";
final String notLeap = " is not a leap year.";
int year;
public leapOrNot() {
Scanner a = new Scanner(System.in);
System.out.println("Enter a year after 1581: ");
year = a.nextInt();
/* if (a.hasNextInt() == false) {
System.out.println("Enter a 4 digit integer: ");
year = a.nextInt();
}
couldn't make this condition work either
*/
while (year < 1582) {
System.out.println("The year must be after 1581. Enter a year after 1581: ");
year = a.nextInt();
continue;
}
if (year % 4 == 0) {
if(year % 400 == 0 && year % 100 == 0) {
System.out.println(year + isLeap);
}
if (year % 100 == 0) {
System.out.println(year + notLeap);
}
else {
System.out.println(year + isLeap);
}
}
else {
System.out.println(year + notLeap);
}
}
}
您应该使用 String.equals()
。替换为这两个中的任何一个
if (quit.charAt(0) == 'x' || quit.charAt(0) == 'X')
if (quit.equals("x") || quit.equals("X"))
以上任何一个都可以正常工作。
或者只使用 if(quit.equalsIgnoreCase("x"))