Java 无法中断while循环。
如果用户输入一个特定的输入,我必须打破循环。但我无法使用if循环来打破while循环。我还尝试在while循环中使用相同的条件,但这也不起作用Java 无法中断while循环。,java,while-loop,conditional,Java,While Loop,Conditional,如果用户输入一个特定的输入,我必须打破循环。但我无法使用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 (t
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);
}
}
}
import java.util.Scanner;
公共班机{
公共静态void main(字符串[]args){
字符串退出;
扫描仪c=新扫描仪(System.in);
while(true){
leapOrNot y=新leapOrNot();
System.out.println(“按x停止或按任何其他字母继续”);
quit=c.next();
如果(退出==“x”|退出==“x”){
打破
}
}
}
}
利波诺级{
最后一个字符串isLeap=“是闰年。”;
最后一个字符串notLeap=“不是闰年。”;
国际年;
公共leapOrNot(){
扫描仪a=新的扫描仪(System.in);
System.out.println(“输入1581年后的年份:”);
年份=a.nextInt();
/*if(a.hasNextInt()==false){
System.out.println(“输入一个4位整数:”);
年份=a.nextInt();
}
也不能让这个条件起作用
*/
而(年份<1582){
System.out.println(“年份必须在1581之后。输入1581之后的年份:”);
年份=a.nextInt();
继续;
}
如果(第%4年==0){
如果(年份%400==0和年份%100==0){
系统输出打印项次(年+isLeap);
}
如果(年份%100==0){
系统输出打印项次(年+非闰年);
}
否则{
系统输出打印项次(年+isLeap);
}
}
否则{
系统输出打印项次(年+非闰年);
}
}
}
您应该使用String.equals()
。替换为这两个选项中的任何一个
if(quit.charAt(0)='x'| quit.charAt(0)='x')
if(quit.equals(“x”)| quit.equals(“x”))
或者只需使用
if(quit.equalsIgnoreCase(“x”)
提示:c.next().toLowerCase()
将有助于减少等式不要使用==
或比较字符串=代码>。请改用equals(…)
或equalsIgnoreCase(…)
方法。了解==
检查两个对象引用是否相同,这不是您感兴趣的。另一方面,这些方法检查两个字符串是否具有相同顺序的相同字符,这就是这里的重点。equalsIgnoreCase
是首选