/*************************************************************************
* Compilation: javac Gambler.java
* Execution: java Gambler stake goal N
*
* Simulates a gambler who start with $stake and place fair $1 bets
* until she goes broke or reach $goal. Keeps track of the number of
* times she wins and the number of bets she makes. Run the experiment N
* times, averages the results, and prints them out.
*
* % java Gambler 50 250 1000
* Percent of games won = 19.0
* Avg # bets = 9676.302
*
* % java Gambler 50 150 1000
* Percent of games won = 31.9
* Avg # bets = 4912.13
*
* % java Gambler 50 100 1000
* Percent of games won = 49.6
* Avg # bets = 2652.352
*
*************************************************************************/
public class Gambler {
public static void main(String[] args) {
int stake = Integer.parseInt(args[0]); // gambler's stating bankroll
int goal = Integer.parseInt(args[1]); // gambler's desired bankroll
int T = Integer.parseInt(args[2]); // number of trials to perform
int bets = 0; // total number of bets made
int wins = 0; // total number of games won
// repeat N times
for (int t = 0; t < T; t++) {
// do one gambler's ruin simulation
int cash = stake;
while (cash > 0 && cash < goal) {
bets++;
if (Math.random() < 0.5) cash++; // win $1
else cash--; // lose $1
}
if (cash == goal) wins++; // did gambler go achieve desired goal?
}
// print results
System.out.println(wins + " wins of " + T);
System.out.println("Percent of games won = " + 100.0 * wins / T);
System.out.println("Avg # bets = " + 1.0 * bets / T);
}
}
我尝试使用此代码,并在线程&#34; main&#34;中获得Exception。 java.lang.ArrayIndexOutOfBoundsException:0我做错了什么?
答案 0 :(得分:4)
此程序接受以阵列形式存储的 Command Line Arguments ,您需要在执行程序时将它们传递给。
从代码中可以看出,应该有三个参数。如果您没有通过它们,您将获得ArrayIndexOutOfBoundsException
。
你需要运行你的程序,
java Gambler 10 20 30
此处10, 20 and 30
是三个命令行参数,将传递给String[] args
,然后在主方法中使用。
如果您尝试按java Gambler
运行程序,那么您肯定会收到异常ArrayIndexOutOfBounds
。
根据@ZouZou的评论:
从Eclipse传递命令行参数:
Run -> Run Configurations -> Argument tabs -> Program arguments and you fill it there.