2014-12-05 1 views
-2
/************************************************************************* 
* 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); 
    } 

} 

나는 "main"스레드에서 예외를 얻습니다. java.lang.ArrayIndexOutOfBoundsException : 0 무엇을 잘못하고 있습니까?스레드 "main"의 예외 java.lang.ArrayIndexOutOfBoundsException : 0 이것은 책 웹 사이트의 코드입니까?

+3

프로그램을 실행할 때 입력을 제공합니까 @ZouZou의 주석 사항에 따라

? 이것은 명시 적으로 클래스의 코멘트에 명시되어 있습니다! _ "java Gambler 50 250 1000"_ –

+0

질문 아래에있는 편집 링크를 사용하여 코드 서식을 수정하십시오. – nop77svk

+0

디버거를 통해 실행 해 보셨습니까? – Biffen

답변

4

이 프로그램은 배열의 형태로 저장된다 Command Line Arguments을 허용하고 당신은 프로그램을 실행하는 동안 그들에게 을 통과해야합니다.

코드에서 볼 수 있듯이 세 개의 인수가 있어야합니다. 전달하지 않으면 ArrayIndexOutOfBoundsException이 표시됩니다. 당신이 좋아하는 프로그램을 실행하는 데 필요한

는 여기 10, 20 and 30

java Gambler 10 20 30

세 가지 명령 줄 인수입니다 다음 주 방법에 사용되는 String[] args에 전달됩니다.

java Gambler으로 프로그램을 실행하려고하는 경우 분명히 예외 ArrayIndexOutOfBounds가 표시됩니다.

이클립스에서 명령 줄 인수를 전달하려면 :

Run -> Run Configurations -> Argument tabs -> Program arguments and you fill it there.

+1

호기심이 많습니다. 미래의 독자들에게도 유용 할 것 같습니다. 식스에서 OP를 실행할 때 OP가 어떻게 이룰 수 있을까요? (인수 추가) –

+3

@BartHofma 실행 -> 실행 구성 -> 인수 탭 -> 프로그램 인수를 입력하면됩니다. –

+0

감사합니다 .. 어쩌면 @GPRathour는 그의 대답에 그것을 추가 할 수 있습니까?, 어쨌든 내 투표를 가지고 있지만 완전한 대답을 위해 :) –

관련 문제