为什么外循环变量不起作用?

时间:2014-07-06 14:18:08

标签: java loops for-loop

我有一个for循环,它将结果存储在一个int数组中,从这些结果我需要能够搜索例如。数组中有多少1,所以我在循环外声明了一个int变量,但它一直说我的数组尚未初始化。你能帮帮我吗。

import java.util.Scanner;
import java.util.Arrays;

class TestDie {

public static void main (String [] args)
{
    Die firstDie = new Die();
    int[] playerOneResults;

    firstDie.roll();
    System.out.println(firstDie.getFaceValue());

    Scanner userInput = new Scanner(System.in);
    System.out.println("PLease enter the name of player one");
    String playerOneName = userInput.next();

    System.out.println("Please enter the name of player two");
    String playerTwoName = userInput.next();

    System.out.println("Enter the number of dice to be thrown");
    int numDice = userInput.nextInt();

    System.out.println("First player's name: " + playerOneName);
    System.out.println("Second player's name: " + playerTwoName);
    System.out.println("Number of dice will be thrown: " + numDice);

    for(int counter = 0; counter != numDice; counter++)
    {
        playerOneResults = new int[numDice];
        firstDie.roll();
        playerOneResults[counter] = firstDie.getFaceValue();
        System.out.println("Player one results: " + playerOneResults[counter]);         
    }

    Arrays.sort(playerOneResults);
    int c = Arrays.binarySearch(playerOneResults, 1);
    System.out.println(c); 


}
}

1 个答案:

答案 0 :(得分:1)

试用此代码

public static void main(String args[]) {
    Die firstDie = new Die();
    int[] playerOneResults = null;

    firstDie.roll();
    System.out.println(firstDie.getFaceValue());

    Scanner userInput = new Scanner(System.in);
    System.out.println("PLease enter the name of player one");
    String playerOneName = userInput.next();

    System.out.println("Please enter the name of player two");
    String playerTwoName = userInput.next();

    System.out.println("Enter the number of dice to be thrown");
    int numDice = userInput.nextInt();

    System.out.println("First player's name: " + playerOneName);
    System.out.println("Second player's name: " + playerTwoName);
    System.out.println("Number of dice will be thrown: " + numDice);

    playerOneResults = new int[numDice];

    for (int counter = 0; counter != numDice; counter++) {
        firstDie.roll();
        playerOneResults[counter] = firstDie.getFaceValue();
        System.out.println("Player one results: " + playerOneResults[counter]);
    }

    Arrays.sort(playerOneResults);
    int position=0;
    while(position<0){
        int c = Arrays.binarySearch(playerOneResults, position,playerOneResults.length-1, 1);
        position=c;
        System.out.println(c);
    }


}