因此,假设我们有一个代码块,我们希望执行70%的次数,另一次执行30%的代码.
if(Math.random() < 0.7)
70percentmethod();
else
30percentmethod();
Run Code Online (Sandbox Code Playgroud)
很简单.但是如果我们希望它可以很容易地扩展到30%/ 60%/ 10%等怎么办?在这里,它需要添加和更改所有关于变化的if语句,这些语句不是很好用,慢和错误诱导.
到目前为止,我发现大型交换机对于这个用例非常有用,例如:
switch(rand(0, 10)){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:70percentmethod();break;
case 8:
case 9:
case 10:30percentmethod();break;
}
Run Code Online (Sandbox Code Playgroud)
哪个可以很容易地改为:
switch(rand(0, 10)){
case 0:10percentmethod();break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:60percentmethod();break;
case 8:
case 9:
case 10:30percentmethod();break;
}
Run Code Online (Sandbox Code Playgroud)
但是这些也有它们的缺点,很麻烦并且分成预定量的分区.
理想的东西将基于我想的"频率数"系统,如下所示:
(1,a),(1,b),(2,c) -> 25% a, 25% b, 50% c
Run Code Online (Sandbox Code Playgroud)
然后,如果你添加另一个:
(1,a),(1,b),(2,c),(6,d) -> 10% a, 10% b, 20% …Run Code Online (Sandbox Code Playgroud) 好的,所以这是我的ArrayList:
private List<ClientThread> clients = new ArrayList<ClientThread>();
Run Code Online (Sandbox Code Playgroud)
这就是我想要做的事情:
我正在尝试删除ArrayList上面发布的最后一个已知项目.我正在尝试使用以下代码执行此操作:
} catch(SocketException re) {
String hey = clients.get(clients.size());
ClientThread.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
}
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
C:\wamp\www\mystikrpg\Server.java:147: incompatible types
found : Server.ClientThread
required: java.lang.String
String hey = clients.get(clients.size());
^
C:\wamp\www\mystikrpg\Server.java:148: cannot find symbol
symbol : method remove(java.lang.String)
location: class Server.ClientThread
ClientThread.remove(hey);
^
2 errors
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?它应该删除我的最后一个已知项目ArrayList.
我发现这个问题的其他条目涉及具体方法,但没有全面的.我想验证自己对这种数据结构中最常用的方法的理解:
O(1) - 恒定时间:
isEmpty()
add(x)
add(x, i)
set(x, i)
size()
get(i)
remove(i)
Run Code Online (Sandbox Code Playgroud)
O(N) - 线性时间:
indexof(x)
clear()
remove(x)
remove(i)
Run Code Online (Sandbox Code Playgroud)
它是否正确?谢谢你的帮助.
我的任务是在ArrayList的新手Java教程中执行以下操作
// 1) Declare am ArrayList of strings
// 2) Call the add method and add 10 random strings
// 3) Iterate through all the elements in the ArrayList
// 4) Remove the first and last element of the ArrayList
// 5) Iterate through all the elements in the ArrayList, again.
Run Code Online (Sandbox Code Playgroud)
以下是我的代码
import java.util.ArrayList;
import java.util.Random;
public class Ex1_BasicArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <= 10; i++){ …Run Code Online (Sandbox Code Playgroud)