【发布时间】:2013-08-18 10:05:14
【问题描述】:
我一直在处理使用 do-while 循环的代码,我想在该循环中添加一个 if else 语句。 do-while 循环检查用户输入的文本,并在输入单词“exit”时结束。
public static void main(String[] args) {
String endProgram = "exit";
String userInput;
java.util.Scanner input = new java.util.Scanner(System.in);
do {
userInput = input.nextLine();
if ( !userInput.equalsIgnoreCase(endProgram) ) {
System.out.printf("You entered the following: %s", userInput);
} else
} while ( !userInput.equalsIgnoreCase(endProgram) );
}
当我尝试编译此代码时,我从命令提示符处收到错误消息:
SentinelExample.java:20: error: illegal start of expression
} while ( !userInput.equalsIgnoreCase(endProgram) );
^
SentinelExample.java:22: error: while expected
}
^
SentinelExample.java:24: error: reached end of file while parsing
}
^
当我删除循环中的 if else 语句时,程序编译得很好。我的程序中的语法有问题吗?还是不能将 if else 语句放在 while 循环中?
【问题讨论】:
-
if语句可以嵌套在while循环中吗?可以
-
你那里有一个无用的 else 关键字
-
嘿,谢谢大家的帮助。只是想知道,为什么我的问题被否决了?
-
@KylerS 无意冒犯你,但有时非常简单的问题会被否决,通常我会尝试对我回答的问题投赞成票
-
@aaronman 好的,嘿,没人接。我是新手
标签: java if-statement while-loop do-while