【发布时间】:2012-03-25 19:15:38
【问题描述】:
1) 我需要使用的第一个循环是 do/while。在这个循环中,提示用户输入一个单词。如果用户输入错误的单词,他们会收到错误消息:
无效!再试一次!还剩 2 次尝试!
无效!再试一次!还剩 1 次尝试!
对不起!你没有更多的尝试了!
只要每次输入错误的单词,此输出就会起作用,但如果在 1 次尝试失败后输入正确的单词,它仍然会应用错误消息
2) 在我的第二个循环(for 循环)中,要求用户输入“3 * 8 =”,如果输入了 3 次错误的数字,或者如果任何尝试都会输入 24。
问题出在输入24之后的循环。输出如下:
谢谢啦啦啦啦。如果您中奖,我们会致电 5555555555。 3 * 8 = 不应显示 3 * 8 的位置。我意识到我可以休息一下;在此语句之后,但说明明确表示我不能使用 break 命令。
正确的输出应该是:Thank you blah blah。如果您中奖,我们会致电 5555555555。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int attempt = 2;
int answer = 24;
long phoneNumber = 0;
String firstName = "";
String lastName = "";
String wordOfTheDay = "";
System.out.printf("Enter the word of the day: ");
wordOfTheDay = input.nextLine();
if(wordOfTheDay.equals("tired"))
{
for( attempt = 2; attempt >= 0; --attempt)
{
System.out.print(" 3 * 8 = ");
answer = input.nextInt();
input.nextLine();
if( answer == 24)
{
System.out.printf( "Please enter your first name, last name, and phone number (no dashes or spaces)\n" +"in a drawing for an all-expenses-paid vacation in the Bahamas: " );
firstName = input.next();
lastName = input.next();
phoneNumber = input.nextLong();
System.out.printf(
"Thank you %s %s. We'll call you at %d if you're a winner.",
firstName,
lastName,
+ phoneNumber);
}
else if( answer != 24)
{
if(attempt!=0)
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
continue;
}
else
{
System.out.print( "Sorry! You have no more attempts left!" );
}
}
}
}
else
{
do
{
System.out.printf( "Invalid! Try Again! %d attempt(s) left!\n ", attempt);
--attempt;
System.out.printf("Enter the word of the day: ");
wordOfTheDay = input.nextLine();
} while (attempt >= 1);
if( attempt == 0)
{
System.out.print( "Sorry! You have no more attempts left!" );
}
}
}
我希望我已经说得够清楚了。
回顾一下,我需要解决我的问题,同时在尝试失败后不让我输入正确的单词。
另外,我需要去掉用户输入正确输入后出现的 3 * 8 =。
【问题讨论】:
-
您为当天的正确单词所做的唯一检查是在两个循环之外,因此在您第一次检查后,无论您输入什么内容,您都不会再检查一次。跨度>
-
我应该把它重新标记为家庭作业吗?
-
您可以尝试改进您的格式吗?例如您的 IDE 将为您执行此操作。
-
我不知道为什么当我粘贴它时它会发生如此大的变化。我正在使用 JCreator,它在那里排列整齐。也许有更好的方法将其复制到窗口中?
标签: java for-loop java.util.scanner do-while