gpt4 book ai didi

java - 我如何随机调用一个方法在java中运行?

转载 作者:行者123 更新时间:2023-11-29 05:54:20 25 4
gpt4 key购买 nike

我正在编写一个将生成几何逻辑词问题的程序,但我遇到了问题。我的目标是让程序随机创建一个预先设计的单词问题。到目前为止,该程序从用户那里获取输入,然后在 Story 方法中使用该信息,有点像 Mad Libs 游戏。无论如何,我想随机选择一个 Story 方法在用户每次启动程序时运行。到目前为止,这就是我所拥有的:

import cs1.Keyboard;
public class LogicProof {
//Main method
public void main () {
System.out.println ("Enter 1. to start.");
System.out.println ("Enter 2. to exit.");
int choice = Keyboard.readInt();
if (choice == 1) { //Take info in and send to createStory

//Randomly run methods

}
if (choice == 2) {
System.out.println ("\nGoodbye.");
}
//Create the first story using inputs from main
private void createStory(String adj,String adj2,String adj3,String action) {

//Use values from main() to create a problem
}

还有另外两个 createStory 方法。另外,我要展示每个问题的证明,每个方法都有自己的证明,那么我是否可以展示相同方法的证明,基本上只是将证明方法和故事方法联系在一起?

我是 Java 的新手,感谢您的帮助。提前致谢。

最佳答案

为了只回答您的标题,您可以使用带反射的随机生成,但这绝不是您解决当前问题的方式。

不要尝试随机调用方法。看看java.util.RandomnextInt() 并使用它根据它返回的值执行独特的操作。

这看起来像是家庭作业,这就是为什么我没有在这里为您提供完整的解决方案。

public class MadLibs {

public static final String[] STARTERS = { /* ... */ };
public static final String[] ENDINGS = { /* ... */ };

public static String generate(String ... adjectives) {
final Random random = new Random();
final StringBuilder string = new StringBuilder(STARTERS[random.nextInt(STARTERS.length-1)]);

for (String adjective : adjectives) {
string.append(adjective);
string.append(TRANSITIONS[random.nextInt(TRANSITIONS.length - 1)]);
}

return string.toString();
}

}

这是一个非常简单和粗略的实现,可以帮助您入门。

或者,如果您只有几个具体的变体:

public class MadLibs {

public static String generate(String ... adjectives) {
int result = new Random().nextInt(MAX);
String madLib = null;

switch (result) {

case 0:
// ...
break;

case 1:
// ...
break;

default:
// ...
break;

}

return madLib;
}

}

关于java - 我如何随机调用一个方法在java中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12756396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com