How to initialize an array of objects and pass an array of strings? - java

I am working on creating a text-based dice game for a school project. The code below is intended to work as follows:
Prompt the user for the number of players playing the game.
Create a string array and prompt the user for the player names and populate the array accordingly.
Create a qwixx object and pass the string array of player names to it.
Create an array of player objects in the qwixx constructor.
Loop through the array of objects and pass a player name from the String array to each object.
Print out all of the players names using the getName() method.
The error I am currently encountering is in the play() method stating that both "players" and "Players" cannot be resolved to a variable. Any help with this is appreciated, new to OOP languages.
import java.util.Scanner;
public class driver {
public static void main(String[] args) {
Scanner input_scanner = new Scanner(System.in);
System.out.print("Please enter the number of players (2-5): ");
numPlayers = input_scanner.nextInt();
String players[] = new String[numPlayers];
for (int x = 0; x < numPlayers; x++) {
System.out.print("Please enter the name of Player" + (x+1) + ": ");
players[x] = input_scanner.next();
}
qwixx game = new qwixx(players);
game.play();
input_scanner.close();
}
}
public class qwixx {
public qwixx(String[] players) {
player[] Players = new player[players.length];
for (int x = 0; x < players.length; x++) {
Players[x] = new player(players[x]);
}
}
public void play() {
for (int i = 0; i < players.length; i++) {
System.out.println(Players[i].getName());
}
}
}
public class player {
public player(String playerName) {
name = playerName;
}
public String getName() {
return name;
}
}

There are a couple of problems with your code. But the most significant one is how in every class other than the one with main, you really have not declared any variable that belongs to the class. Do not introduce the class variables inside the constructors. Declare them outside the constructor so they can be global variables. Try:
public class qwixx {
player[] Players; //declared before using it in any methods / constructor
public qwixx(String[] players) {
Players = new player[players.length]; //value initialized inside the constructor
for (int x = 0; x < players.length; x++) {
Players[x] = new player(players[x]);
}
}
public void play() {
for (int i = 0; i < Players.length; i++) {
System.out.println(Players[i].getName());
}
}
}
Similarly, try doing the same in your player class:
public class player {
String name;
public player(String playerName) {
name = playerName;
}
public String getName() {
return name;
}
}
And on your main, you forgot to declare numPlayers as int. Do that too.
int numPlayers = input_scanner.nextInt

First , You have instantiated much of your data inside the main method causing your operating code to be static!
Second the following line is not declared global "but requires using static" so can only be seen inside the static main method.
String players[] = new String[numPlayers];
"public class qwixx" to use in the main method should be "public static class qwixx"
The following is a "new instance" not static
qwixx game = new qwixx(players);
but the problem to call it then becomes as below, because a static class is not declared new, it is simply called with a method that requires using
qwixx.play();
More than that any class name is better written by its convention of starting with an UPPER case letter to both assist reading the code and the compiler to not trip over. e.g. "public static class Qwixx"
"Remove the static contexts" OR work completely within them , one or the other ONLY.

Related

NullPointerException when accessing an internal Object attribute of an initialized object

I have two classes, Car and Tire, with the following funcitons.
Tire:
public static class Tire{
public boolean isBroken;
public int milesLeft;
public Tire(){
isBroken = false;
milesLeft = 100;
}
public void copyTire(Tire anotherTire){
isBroken = anotherTire.isBroken;
milesLeft = anotherTire.milesLeft;
}
public int getMilesLeft(){
return milesLeft;
}
}
Car
public static class Car{
public boolean maintenance;
public String name;
public Tire tires[] = new Tire[MAX_TIRES];
public Tire LF = new Tire();
public Car(String name){
maintenance = false;
this.name = name;
}
public String getName(){
return name;
}
}
My problem is that I want to print the information (milesLeft) from all the tires of the car's array. I assumed it would work simply by using a for loop, but it doesn't and I dont know why.
This is what I tried:
for(int i = 0; i < MAX_TIRES; i++){
System.out.println("Tire nº"+i+": "+ i20.tires[i].getMilesLeft());
}
While printing an only tire, the LF we have in the car's class, there's no problem.
Any other errors you may see write them too, I've studied c++ but I'm starting with Java.
EDIT:
The error:
Exception in thread "main" java.lang.NullPointerException
at vehicles.main(vehicles.java:56)
The declaration of car with the 'main' function.
public static void main(String []args) {
Car i20 = new Car("i20");
System.out.println("The name is " + i20.getName());
System.out.println("The tires' status right now is:");
for(int i = 0; i < MAX_TIRES; i++){
System.out.println("Tire nº"+i+": "+ i20.tires[i].getMilesLeft());
}
}
I thought that when creating a new car, it would create the tires too
Computers are stupid. You didn't tell it to create tyres whenever cars are created, so it didn't do it for you. That's why when you try to access the tyres, a NullPointerException is thrown. The tyres have not been created yet!
After you create your car, also create the tyres:
Car i20 = new Car("i20");
for (int i = 0 ; i < i20.tires.length l i++) {
i20.tires[i] = new Trie();
}
Now the tyres are created. Then you can print the tyres using the for loop.
You can also put this tyre creation code in the constructor. Your Car class' constructor can look something like this:
public Car(String name){
maintenance = false;
this.name = name;
for (int i = 0 ; i < this.tires.length ; i++) {
this.tires[i] = new Tire();
}
}

Loop not recognizing variables previously defined

I'm working on a Guessing Game that will uses arrays to store both the names of all the players and their guesses. I'm fairly new to arrays, so my plan to get user input into the array was to get them to enter the amount of people playing, set that up as a variable and then use a loop to keep asking for names until I reached the necessary amount of names for the stated number of players. However, I am running into what probably is a very simple problem with the loop. Here's a small bit of my code thus far:
public class GuessGame {
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
The problem is, I'm getting an error regarding the variables in my loop, w and j. The error statement says something to the effect of it cannot find the symbols for class w or class j. I don't intend for them to be classes, and I've run similar code in other projects without a hitch, so I really don't know what's going wrong here. I'm sure it's something stupidly simple, but *'ve been stuck at this wall for some time now and can't really progress until I get this sorted. This is part of a project with three separate classes. The class posted here, a Player class, and a Tester class, which is my main method. I had the whole thing working in a more simplified form earlier, but now I need to adjust it for actual player input and the arrays. Regardless, the tester class is supposed to be my main class. I am using Netbeans if it matters. Thank you. Here are the other two classes for reference:
package GuessGame;
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
and
package GuessGame;
import java.util.Random;
public class Player {
int number = 0; //where guess goes
String name;
public void guess() {
Random r = new Random();
number = 1 + r.nextInt(21);
System.out.println("I'm guessing " + number);
}
}
All your code needs to be in a method. You cannot have anything except variable declarations at the class level. Move all this into a method, for example public static void main(String[] args) main method.
public class GuessGame {
public static void main (String[] args)
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
public class GuessGame {
public void getPlayerName()
{
int w = 0;
int[] Players = new int[100];
String[] PlayerNames = new String[100];
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
public static void main (String[] args)
{
GuessGame gg = new GuessGame();
g.getPlayerName();
}}
You can put in the methos as well and execute in the main method. But, if you declaring any variable inside the method (local variable), the variable must be initialised. Refer here for more details.
public class GuessGame
{
static int w = 0;
int[] Players = new int[100];
static String[] PlayerNames = new String[100];
public static void main(String[] args) {
// TODO Auto-generated method stub
String numStart = JOptionPane.showInputDialog("How many players?");
int j = Integer.parseInt(numStart);
while (w <= j)
{
String Name = JOptionPane.showInputDialog("What is your name?");
PlayerNames[w] = Name;
w++;
}
}
}
Everything should be in a method except variables.Class is template for variables and methods !!

Can I call a method which I create in another class in my current class in java?

I want to create a program for a simple game. The game has 3 classes:
Player: contains player details like username, family name and
last name
Nimsys: the system containing all the methods for the game
functions, can have up to 100 players
NimGame: 1 game is played by 2 players only
Question: I have created the 3 classes but I don't know how to link the classes together. How do I add a player name using Scanner and StringTokenizer to separate the username, family name and last name? Should my main method be in NimGame class? In my code, when I call NimPlayer.addPlayer(), it has error message that the method addPlayer is undefined for type NimPlayer. Please help how to use method addPlayer??
So far my code looks like this:
public class NimGame
{
int currentStoneCount, stoneRemovalUpperBound;
private NimPlayer player1, player2;
public static void main (String [] args)
{
System.out.println ("Welcome to Nim");
System.out.println("\n>");
**NimPlayer.addPlayer();**
}
public class NimPlayer
{
String userName, givenName, familyName, newFamilyName, newGivenName;
int gamesPlayed, gamesWon, gamesLost;
/*Constructor*/
public NimPlayer (String userName, String givenName, String familyName,
String newFamilyName, String newGivenName)
{
this.userName = userName;
this.givenName = givenName;
this.familyName = familyName;
this.newFamilyName = newFamilyName;
this.newGivenName = newGivenName;
}
}
import java.util.Scanner;
java.util.StringTokenizer;
public class Nimsys
{
public static void addPlayer()
{
Scanner keyboard = new Scanner (System.in);
String [ ] player = new String [100]; //an array of 100 players
for (int i = 0; i < 100; i++)
{
boolean isInArray = false;
String NimPlayer = keyboard.next();
String delimiters = " add player, "; //add player, comma and blank space
StringTokenizer nameFactory = new StringTokenizer (NimPlayer, delimiters);
String userName = nameFactory.nextToken();
String familyName = nameFactory.nextToken();
String givenName = nameFactory.nextToken();
if (i>0)
{
for (int j = 0; j < 100; j++)
{
if (player [j].equalsIgnoreCase(userName))
{
isInArray = true;
System.out.println("The player already exists.");
System.out.println("\n>");
}
else
{
player [j] = NimPlayer;
System.out.println("\n>");
}
}
}
}
}
}
I think you want
NimSys.addPlayer();
This is badly broken:
player [j] = NimPlayer;
You might mean
player [j] = new NimPlayer( ...,...,... );
with all the many (too many?) parameters the NimPlayer constructor expects. But then again, player is a String array, so you should change this definition.
And why do you think you need 100 players?
In support of what laune said, you can't call
NimPlayer.addPlayer();
because your addPlayer method is in the class NimSys, not NimPlayer. And your
String [ ] player = new String [100]; //an array of 100 players
needs to be of type NimPlayer because it holds NimPlayers, not strings. And in order to be able to add/edit later, I'd change it to a List:
List<NimPlayer> player = new ArrayList<NimPlayer>(); //an array of x amount of players
From what I can gather about your code, it seems that the best approach may be to create a constructor with no parameters in your NimPlayer class
public NimPlayer(){
}
create a new NimPlayer
currentPlayer = new NimPlayer();
and assign the values like this:
currentPlayer.userName = nameFactory.nextToken();
currentPlayer.familyName = nameFactory.nextToken();
currentPlayer.givenName = nameFactory.nextToken();
From there you could compare this currentPlayer to all the other NimPlayers in your array by comparing usernames:
for (int j = 0; j < player.size(); j++)
{
NimPlayer storedPlayer = player.get(j);
if (storedPlayer.userName.equalsIgnoreCase(currentPlayer.userName))
{
isInArray = true;
System.out.println("The player already exists.");
System.out.println("\n>");
}
else
{
player.add(currentPlayer);
System.out.println("\n>");
}
}

Setting values to parameters in a constructor in Java

I just wanted to ask basically what the title says. Here's my example and I want x to be the new set random. I also am doing this off a phone switch doesn't support an equal sign so - means equal. Also the bracket is (. So when I do
Constructor a - new Constructor(x)
public class Opponent (
public static x - 0;
public Opponent (int value) (
value - 5;
)
public static void main (String() args) (
Opponent character1 - new Opponent(x)
System.out.println(x);
)
)
Basically I want x to become 5. The game I am developing concerns randomization then the values should give them to the parameter to the newly created character.
Problem I am having is that its not working which means it probably can't do this.
Is there anyway I can do this.
I apologize if it is a dumb question though but anyways thanks.
I honestly don't know what your question is, but try running this:
public class Opponent {
public int x;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
Opponent character1 = new Opponent(5);
System.out.println(character1.x); // this will output: 5
}
}
A few problems with your question:
you are trying to initialize a static variable thinking its an instance variable?
x is not initialized in main()
value is not defined as a field in Opponent
public class Opponent {
public static int x = 0;
public Opponent (int value) {
x = value;
}
public static void main (String[] args) {
int y = 5; // random number I chose to be 5
Opponent character1 = new Opponent(y);
System.out.println(character1.x + ""); // will display 5 (which was int y)
}
}
List of Problems:
• To open/close a method/class, don't use ( and ); you have to use { and }
• public static void main (String() args) needs to be public static void main (String[] args)
• To initialize something, use =, not -.
• You need to give x a type, such as int.
• When you defined Opponent character1 - new Opponent(x), you need to have a semi-colon at the end.
• You passed x as a parameter in the line Opponent character1 = new Opponent(y);, even though you were trying to define x with the parameter. Give it a different value.
One note: why would you define an instance of the class in the class? Instead of using this:
Opponent character1 = new Opponent(y);
System.out.println(character1.x + "");
You could just write this:
System.out.println(Opponent.x + "");
However, you could create character1 if you were accessing class Opponent from a different class.
maybe something like this. i leave the random number generation up to you:
public class Opponent
{
private int score;
public Opponent()
{
// you probbaly want to override this with
// a random number generator
this.score = 0;
}
public Opponent(int value)
{
this.score = value;
}
public int getScore()
{
return this.score;
}
public void setScore(int score)
{
this.score = score;
}
public static void main(String[] args)
{
Opponent character1 = new Opponent();
Opponent character2 = new Opponent(5);
int result = character1.getScore() - character2.getScore();
System.out.println(result);
}
}

storing command line args in an array class

Musical Chairs. Musical Chairs is a children’s game where the players walk around a group of chairs while some music is playing. When the music stops, everyone must sit down. But, there is one less chair than there are people, so someone gets left out. And, indeed, that person is out of the game. A chair is removed. And the game is played again; someone else goes out. This continues until there is only one player left, the winner.
I am having problems storing the command line arguments in the player[]
here is my code
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
You're not storing the arguments in your array. If your question is how to do it, then you should:
Initialize the players array.
For each argument, you must create a Player object and store it in the array.
Use the data in your program.
This could be done like this:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
The question is still open: What's your specific problem?
I think you need to update your code to create new players and maintain the reference in your array...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}

Resources