问题描述
我在Java领域还比较陌生,并且正在为一个类编写程序.我已经对所有代码进行了编码,并且运行良好,但是当我键入字符串"exit"时,我需要退出一个方法.我当前的代码将在下面.我必须按照作业分配3种方法(包括main)和一个"while"循环(或do-while,但我的教授禁止我们使用这些方法).这是一个魔术八球"程序,while循环设置为继续询问问题,直到用户键入"exit"为止,但我似乎无法让我的"while"循环正常工作.如果我输入exit作为第一个字符串,它将像预期的那样退出,但是,如果我键入任何其他字符串,即使我键入exit,它也将继续运行,并且基本上变成一个无限循环的问题/答案.感谢您的帮助.
I'm still relatively new at Java and am working on a program for class. I have everything coded up and it's working great, but I need to exit a method when I type the string "exit". My current code will be below. I must have 3 methods (includes main) and a "while" loop (or do-while, but my professor has barred us from using those) as per the assignment. It's a "magic eight ball" program and the while loop is set to continue asking questions until the user types "exit" but I can't seem to get my "while" loop to work correctly. If I type exit as the first string it'll exit like it's supposed to, but if I type any other string it'll keep running, even after I type exit, and basically becomes an infinite loop of questions/answers. Any help is appreciated.
请注意,switch语句中的这些数字纯粹是用于将来答案的占位符,因此请忽略它们.
A side note, those numbers in the switch statement are purely place holders for future answers, so ignore them.
import java.util.*;
public class FirstProblem {
public static void main (String [] args) {
getQuestion();
}
public static String getQuestion () {
Scanner input = new Scanner (System.in);
System.out.print ("Ask any question you need answered and prepare yourself for the sage advice of......your computer.\nJust type \"exit\" when you can't handle the truth any longer.\nQuestion: ");
String question = input.nextLine();
String exit = "exit";
showAnswer();
while (!question.equals(exit)) {
getQuestion();
}
return question;
}
public static void showAnswer () {
int answer = (int)(Math.random() * 10);
switch (answer) {
case 0: System.out.println ("1"); break;
case 1: System.out.println ("2"); break;
case 2: System.out.println ("3"); break;
case 3: System.out.println ("4"); break;
case 4:System.out.println ("5"); break;
case 5:System.out.println ("6"); break;
case 6:System.out.println ("7"); break;
case 7: System.out.println ("8"); break;
case 8: System.out.println ("9"); break;
case 9: System.out.println ("10"); break;
}
return;
}
}
推荐答案
您的问题在以下代码中:
Your problem is in this code:
showAnswer();
while (!question.equals(exit)) {
getQuestion();
}
如果您不知道在此处进行什么递归操作,则可以进行递归调用,网址为维基百科
This is doing a recursive call, if you don't know what recursion is read about it here at Wikipedia
解决方案是将其更改为:
The solution would be to change it to:
while (!question.equals(exit)) {
showAnswer();
System.out.print("Question: ");
question = input.nextLine();
}
这是Ideone上的代码段.
Here's the code snippet on Ideone.
这篇关于退出带有特定字符串的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!