我编写了一个神奇的8球程序,具有20种不同的可能响应。每次随机选择一个响应时,我都会尝试将该响应写入文件中。但是,在main方法的do-while循环中,行“ writeFile(answer);” 不起作用,因为“答案”超出范围。我在尝试修复它时遇到了麻烦。
import java.io.*;
import java.util.*;
public class App {
public static void main(String[] args) {
String terminate = "Q";
String Question = "";
System.out.println("I am the all-knowing Magic 8 Ball!");
String something = "This is an easter egg!";
do {
Scanner scnr = new Scanner(System.in);
System.out.println("");
System.out.println("Ask your question here or enter 'Q' to quit:");
Question = scnr.nextLine();
continueGame(Question);
writeFile(answer);
} while (!(terminate.equals(Question)));
}
public static void continueGame(String Question) {
char terminate = 'Q';
char condition = Question.charAt(0);
if (condition == terminate)
{
System.out.println("");
System.out.println("Thanks for playing!");
System.exit(0);
}
try
{
Random rand = new Random();
int choice;
choice = 1 + rand.nextInt(20);
responseOptions(choice, Question);
}
catch (Exception e)
{
System.out.println("Error: Invalid");
}
}
public static String responseOptions(int choice, String answer)
{
switch (choice)
{
case 1: answer = "Response: It is certain"; break;
case 2: answer = "Response: It is decidely so"; break;
case 3: answer = "Response: Without a doubt"; break;
case 4: answer = "Response: Yes, definitely"; break;
case 5: answer = "Response: You may rely on it"; break;
case 6: answer = "Response: As I see it, yes"; break;
case 7: answer = "Response: Most likely"; break;
case 8: answer = "Response: Outlook good"; break;
case 9: answer = "Response: Yes"; break;
case 10: answer = "Response: Signs point to yes"; break;
case 11: answer = "Response: Reply hazy, try again"; break;
case 12: answer = "Response: Ask again later"; break;
case 13: answer = "Response: Better not tell you now"; break;
case 14: answer = "Response: Cannot predict now"; break;
case 15: answer = "Response: Concentrate and ask again"; break;
case 16: answer = "Response: Don't count on it"; break;
case 17: answer = "Response: My reply is no"; break;
case 18: answer = "Response: My sources say no"; break;
case 19: answer = "Response: Outlook not so good"; break;
case 20: answer = "Response: Very doubtful"; break;
}
System.out.println("");
System.out.println(answer);
return answer;
}
public static String writeFile(String something) {
try {
FileWriter fw = new FileWriter("filename.txt", true);
fw.write(something);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
return something;
}
}
首先,我将略微更改responseOptions
方法。它只需要选择参数:
public static String responseOptions(int choice) {
String answer;
switch (choice) {
// ...
然后,我们应该更改continueGame
一下:
public static String continueGame(String Question) {
// ...
return responseOptions(choice);
}
catch (Exception e)
{
return"Error: Invalid"
}
}
最后,主要
// ...
String answer = continueGame(Question);
// ...
因此,基本上,我们将来自responseOptions方法的答案返回给main,以便能够将其传递给print方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句