Thursday, November 28, 2013

Creating multiple Objects using for loop.








I'm creating the game of monopoly, star wars edition for fun, not for homework :) Anyways I'm prompting the user to input how many 'human' players they want out of 4 players in total. Then I use a for loop to create that amount of human players. That seems to work however when I use a getter method to test and see if the players survive outside the loop, it says "cannot find symbol - variable player." This was my first attempt at using arrays as well. So If someone could assist me on accessing and using those created unique player objects, that would be great. Here's my code.












Java Code:











import java.util.Scanner;
import java.util.Random;
public class Launcher
{
PairOfDice myDice = new PairOfDice();
private Planet myTest;
private PlanetInfo myPlanetInfo;
public static void main(String[] args)
{

Scanner scan = new Scanner(System.in);
System.out.println("You are in the presence of the Naked Jeff's code. Please, be humbled.");
System.out.println();
System.out.println("There will be 4 players, how many do you wish to be human? 0><4");

////////////////////////////////////////////////////////// HOW TO CREATE MULTIPLE OBJECTS BASED ON LOOP
int numbHuman = scan.nextInt();
while (numbHuman < 1 || numbHuman > 4)
{
System.out.println("Invalid entry, try again.");
numbHuman = scan.nextInt();
}
Player[] arr = new Player[numbHuman];
String[] userName = new String[numbHuman];
for(int i = 0; i < arr.length; i++)
{
System.out.println("Player " + (i + 1) + ", Please enter your first name:");
userName[i] = scan.next();
arr[i] = new Player(userName[i]);
}
System.out.println("player " + (4) + "'s name is" + player[3].getName());
/////////////////////////////////////////////////////////
}
}









and here's my Player class.







Java Code:











public class Player
{
PairOfDice myDice = new PairOfDice();
private int startingBal;
private int currentBal;
private String myName;
private int rollOne;
private int rollTwo;
private int doublesCount;
private boolean roll;

public Player(String userName)
{
myName = userName;
System.out.println("Player's name is: " + myName);
}
public String getName(){return myName;}
public int playerGo()
{
myDice.rollDice();
rollOne = myDice.getResult1();
rollTwo = myDice.getResult2();
while(rollOne == rollTwo && roll == true)
{
doublesCount++;
roll = false;
//WORKING ON THIS//
}
return 0;
}
public boolean getGoAgain(boolean roll)
{
return roll;
}
public int newBalance()
{

return 1;
}
}
















No comments:

Post a Comment