gpt4 book ai didi

java - 随机调用文本文件中不同命令的百分比

转载 作者:行者123 更新时间:2023-12-02 00:22:54 24 4
gpt4 key购买 nike

这是我的配置文件(Test.txt)

CommandA   75%
CommandB 15%
CommandC 10%

我编写了一个多线程程序,在其中逐行读取文件,但不确定我应该如何解决上述问题,其中这么多百分比(75%)的随机调用转到 CommandA,而这么多百分比(15 %) 的随机调用转到 CommandB,与 CommandC 相同。

public static void main(String[] args) {

for (int i = 1; i <= threadSize; i++) {
new Thread(new ThreadTask(i)).start();
}
}

class ThreadTask implements Runnable {

public synchronized void run() {
BufferedReader br = null;

try {
String line;

br = new BufferedReader(new FileReader("C:\\Test.txt"));

while ((line = br.readLine()) != null) {
String[] s = line.split("\\s+");
for (String split : s) {
System.out.println(split);
}
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

}
}

最佳答案

获取一个 1-100 之间的随机数。如果数字是1-75执行命令A,76-90执行命令B,91-100执行命令C。

已编辑评论:

我会考虑通过两种方式来做到这一点。如果您只有三个命令(A、B、C),那么您可以执行简单的操作:

    int[] commandPercentages = {75, 15, 10};        
int randomNumber = 90;

if((randomNumber -= commandPercentages[0]) < 0) {
//Execute Command A
}
else if((randomNumber -= commandPercentages[1]) < 0) {
//Execute Command B
}
else {
//Execute Command C
}

如果您有很多复杂的命令,您可以像这样设置命令:

private abstract class Command {
int m_percentage;
Command(int percentage) {
m_percentage = percentage;
}
int getPercentage() {
return m_percentage;
}
abstract void executeCommand();
};

private class CommandA extends Command {
CommandA(int percentage) {
super(percentage);
}
@Override
public void executeCommand() {
//Execute Command A
}
}

private class CommandB extends Command {
CommandB(int percentage) {
super(percentage);
}
@Override
public void executeCommand() {
//Execute Command B
}

}

然后选择命令,如下所示:

    Command[] commands = null;  
int randomNumber = 90;

commands[0] = new CommandA(75);
commands[1] = new CommandB(25);

for(Command c: commands) {
randomNumber -= c.getPercentage();
if(randomNumber < 0) {
c.executeCommand();
}
}

关于java - 随机调用文本文件中不同命令的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607614/

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