Add objects in an ArrayList through constructor - java

I am a beginner, and I am building a classical NimGame. Before, I used to save the project using an array. Now, I modify it to apply the ArrayList to this time. It seems no problem, though, the functions I've made are not working without any errors. I couldn't figure out why.
For now, I tried to add the NimPlayer type into the new playerList, which is the ArrayList. I put the ArrayList in the NimModel, and use the constructor from the NimPlayer to create new players. The Nimsys is the main panel to give commands and receive user inputs. That's why I separate them into three classes.
The command is like this
$addplayer userName,familyName,givenName. And the scanner should process the string and go through the constructor to be a new object.
Any help is highly appreciated, and thank you for your kindness and patience.
Here is my related code Nimsys:
public class Nimsys {
private NimModel nimModel;
public static void main(String[] args) {
Nimsys nimsys = new Nimsys();
nimsys.processCommands();
}
private void processCommands() {
this.nimModel = new NimModel();
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Nim\n");
while (true) {
System.out.print('$');
String commandin = in.nextLine().trim();
if (commandin.equalsIgnoreCase("addplayer")) {
addplayer(in);
}
if (commandin.equalsIgnoreCase("removeplayer")) {
removeplayer(in);
}
}
private String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
private void addplayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
ArrayList<NimPlayer> playerList = nimModel.getPlayerList();
for (NimPlayer player: playerList) {
if (player.getUserName().contains(name[0])) {
System.out.println("The player already exists.");
return;
} else {
nimModel.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
}
}
}
private void removeplayer(Scanner in) {
String removeUserName = in.nextLine().trim();
NimPlayer player = nimModel.removePlayer(removeUserName);
if (player == null) {
System.out.println("The player does not exist");
} else {
System.out.println("Player " + player.getUserName() +
" removed successfully!");
}
}
And the NimModel:
public class NimModel {
private NimPlayer nimplayer;
private ArrayList<NimPlayer> playerList = new ArrayList<>();
public void createPlayer(String userName, String familyName, String givenName) {
NimPlayer player = new NimPlayer(userName, familyName, givenName);
playerList.add(player);
}
public ArrayList<NimPlayer> getPlayerList() {
return playerList;
}
public NimPlayer removePlayer(String userName) {
for (NimPlayer player: playerList) {
String nameCheck = nimplayer.getUserName();
String playerName = player.getUserName();
if (playerName.equals(nameCheck)) {
playerList.remove(player);
break;
}
}
return null;
Lastly, NimPlayer class
public class NimPlayer {
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
private int winRatio;
public NimPlayer(String userName, String familyName, String givenName) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
//getters and setters
}

When you use scanner.nextLine() you are asking for a new input to the user. So if you want the format: $addplayer user,firstName,lastName you have to fetch it into a string and use this string:
while (true) {
System.out.print('$');
String commandin = in.nextLine().trim();
if (commandin.split(" ")[0].equalsIgnoreCase("addplayer")) {
addplayer(commandin);
}
}
}
private void addplayer(String commandin) {
String inName = commandin.split(" ")[1];
String[] name = splitName(inName);
....

in a nutschell:
private void addplayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
ArrayList<NimPlayer> playerList = nimModel.getPlayerList();
for (NimPlayer player: playerList) {
if (player.getUserName().contains(name[0])) {
System.out.println("The player already exists.");
return;
}
}
nimModel.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
}
Furthermore, your addPlayer() given in Nimsys is defined in your While(true) but I think it's more a typing error.
Personally I would also give a constructor to your model:
import java.util.ArrayList;
public class NimModel {
private NimPlayer nimplayer;
private ArrayList<NimPlayer> playerList;
public NimModel()
{
this.playerList = new ArrayList<NimPlayer>();
}
public void createPlayer(String userName, String familyName, String givenName) {
NimPlayer player = new NimPlayer(userName, familyName, givenName);
playerList.add(player);
}
public ArrayList<NimPlayer> getPlayerList() {
return playerList;
}
public NimPlayer removePlayer(String userName) {
for (NimPlayer player : playerList) {
String nameCheck = nimplayer.getUserName();
String playerName = player.getUserName();
if (playerName.equals(nameCheck)) {
playerList.remove(player);
break;
}
}
return null;
}
}

Related

How to modify code to add a quit option in the menu and keep it looping until it is called?

I am working on a Java text-based adventure game and want to change my code to add a Quit option as a fourth item and keep it looping until the user chooses to quit based on the respective choice. I originally had it so that it would run 10 times inside a while loop, but I decided I wanted the user to have control when they want to quit and end the program.
Here is what I have so far:
Game.java
public class Game {
private static Room library, study, ballroom, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
initialSetupGame();
int rounds = 10;
while(rounds > 0) {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
rounds--;
}
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
study = new Room("Study");
ballroom = new Room("Ballroom");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(study);
library.addConnectedRoom(ballroom);
library.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(ballroom);
study.addConnectedRoom(kitchen);
ballroom.addConnectedRoom(library);
ballroom.addConnectedRoom(study);
ballroom.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(ballroom);
kitchen.addConnectedRoom(study);
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name: ");
String playerName = input.nextLine();
System.out.println(playerName + "? Wow, that's a neat name!"
+ "\nWelcome to Aether Paradise, a game where you can explore"
+ " the the majestic hidden rooms of Aether. Let's begin!");
// Set the player to start in the library
currentLocation = library;
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.println("{Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
}
Room.java
public class Room {
private String name;
private String description;
private ArrayList<Room> connectedRooms;
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
public Room getConnectedRoom(int index) {
return connectedRooms.get(index);
}
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
Use java.util.Scanner to read input and check the entered value:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? [Y]es/[N]o");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
}

How to check the duplicate object in the array

I am a java beginner and I am designing a Nim game for many players to join. I've done some research but I don't know if my implementation is correct. The aim is to check the duplicate object in an array. I've already checked some articles, and I'll reference them in the last part of this article.
For the NimPlayer class. I've created some things.
I've defined the NimPlayer object type.
Using the type, I can initialize the player in the limited space.
I initialize an array for saving player's data by following the steps here: Storing object into an array - Java
public class NimPlayer {
String userName;
String familyName;
String givenName;
NimPlayer [] playerList = new NimPlayer[10]; //set an array here
int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
//create new data using NimPlayer data type
public void createPlayer(String userName, String familyName, String givenName) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
}
In the main method, I have created some features for players to use:
addplayer - let the user can add players in the game to compete.
To add the player, the Syntax like this:
$addplayer userName,familyName,givenName
to validate the input, I split the input and store them in the new object.
public static String[] splitName(String inputName) {
String [] splittedLine = inputName.split(",");
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
String [] name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
return name;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create new object to save data
NimPlayer playerData = new NimPlayer(null, null, null);
System.out.print('$');
String commandInput = in.next();
while (true) {
if (commandInput.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
String userName = name[0];
String familyName = name [1];
String givenName = name[2];
playerData.createPlayer(userName, familyName, givenName);
for (int i = 0; i < playerData.playerList.length; i++) {
NimPlayer player = playerData.playerList[i];
System.out.println(player.getUserName()); }
}
So far, I have two questions here.
Every time I enter a set of data, it seems my "playerData" provokes the NullPointerException when looping through the object, but since my name input is multiple, I have to create a new object in the main method for saving input.
For checking if there is the duplicate "userName" in the set of the "inputName", I loop through the objects in an array. How can I access the "userName" in this situation?
for checking duplicate, I've checked:
Java - Loop through instances of a class rather than calling a method for each separate instance
What is a NullPointerException, and how do I fix it?
Java Array, Finding Duplicates
You should address then following things in your design/code:
Since you are creating a player using createPlayer(String userName, String familyName, String givenName), you should make the constructor, NimPlayer(String userName,String surName, String givenName) private so that it can not be called from outside of the class, NimPlayer. Also, declare createPlayer as static so that it doesn't need a NimPlayer object to be called on.
You need to have a static counter to keep track of the number of players and check the value of this counter before adding a new player to playerList.
You should also check the size of the resulting array after inputName.split(","). Similarly, you should check the size of the returned array from splitName before you access any element from it.
Given below is the code incorporating the points mentioned above:
import java.util.Scanner;
class NimPlayer {
private String userName;
private String familyName;
private String givenName;
//...
// public getters and setters of userName, familyName, and givenName
//...
private static int counter = 0;
private static NimPlayer[] playerList = new NimPlayer[10];
private NimPlayer(String userName, String familyName, String givenName) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
}
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < 10) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("The list is full.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer[] getPlayers() {
return playerList;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandInput = in.next();
if (commandInput.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
if (name != null && name.length == 3) {
NimPlayer.createPlayer(name[0], name[1], name[2]);
}
} else {
break;
}
}
for (int i = 0; i < NimPlayer.getCounter(); i++) {
System.out.println(NimPlayer.getPlayers()[i].getUserName());
}
}
public static String[] splitName(String inputName) {
String[] splittedLine = inputName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
}
I didn't understand your another question:
For checking if there is the duplicate "userName" in the set of the
"inputName", I loop through the objects in an array. How can I access
the "userName" in this situation?

How can i verify if i'm adding atributes to a list that are equal?

import entidades.*;
public class Main {
public static void main(String[] args) {
Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop == true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.nextLine();
String categoriaPro = sc.nextLine();
prof.NomeVerificacao(profissional, nomePro, categoriaPro);
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissional) {
System.out.println(pro);
This is my Main, it's running fine but i don´t think it is adding the atributes to the list and not verifying either.
i want to add the atributes to a list so i can create different objets but they can not have at least the name equal.
public class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
public void NomeVerificacao(List<Profissional> profissional ,String nome, String categoria) {
if(profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
}else {
for(Profissional pro : profissional) {
if(pro.nome.contentEquals(nome)) {
System.out.println("Já Exite esse nome");
}else {
profissional.add(new Profissional(nome, categoria));
}
}
}
}
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
this is the Profissional Class.
I'm almost there i think but the output keeps saying that the name exists even though it is the first name i'm inserting.
I ran your code on my machine and made 3 changes into it, and it's working for me now,
1)
String nomePro = sc.next();
String categoriaPro = sc.next();
2) In professional class just changed this function a bit:
public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
if (profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
} else {
int i = 0;
for (; i < profissional.size(); i++) {
if (profissional.get(i).nome.equals(nome)) {
System.out.println("Já Exite esse nome");
break;
}
}
if (i == profissional.size()) {
profissional.add(new Profissional(nome, categoria));
}
}
}
3) At the end of the class Main, wrote sc.close(); to close the scanner.
i/p and o/p :
1) RP
red
color
2) RP
orange
color
3) RP
orange
paint
Já Exite esse nome
4) SAIR
nome=red, categoria=color
nome=orange, categoria=color
As you can see in above i/p and o/p, nome=red and nome=orange with categoria=color are added in the list but when we tried to add the same nome=orange again but with different category as paint it didn't add it and printed the message "Já Exite esse nome".
and after entering SAIR, the toString(); printed the list content at the end. So the message will be printed only if we try to add the object with the same name again int list (not the first or any other times).
Further optimizations are possible but for now, it will work!
I can propose the following solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Set is a data structure that makes sure you don't have a duplicated elements
// in this case we use TreeSet structure that accepts comparator which tells that
// we need to compare elements only by professional's name
Set<Profissional> profissionals = new TreeSet<>(Comparator.comparing(Profissional::getNome));
while (true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.next();
String categoriaPro = sc.next();
// add function returns true in case the element we're going to add
// was not presented in Set structure yet. False otherwise.
boolean isNew = profissionals.add(new Profissional(nomePro, categoriaPro));
if (!isNew) {
System.out.println("Professional with name " + nomePro + " already exists");
} else {
System.out.println("Professional with name " + nomePro + " was added");
}
} else if (comando.contentEquals("SAIR")) {
break;
}
}
// just prints all professionals at the end of the program
profissionals.forEach(System.out::println);
}
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
// getters and setters
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
The output will be the following:
RP
test test
Professional with name test was added
RP
test1 test1
Professional with name test1 was added
RP
test test3
Professional with name test already exists
SAIR
nome=test, categoria=test
nome=test1, categoria=test1
package javaapplication8;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JavaApplication8 {
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
}
public static void main(String[] args) {
try {
List<Profissional> profissionalList= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\r\nEnter comando:");
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
System.out.print("nome: ");
String nome = sc.next();
sc.nextLine(); // wait enter
System.out.print("categoria: ");
String categoria = sc.next();
sc.nextLine(); // wait enter
// access constructor of Profissional
Constructor profCtor = Profissional.class.getConstructor(String.class, String.class);
profCtor.setAccessible(true);
// create instance of Profissional
Profissional newItem = (Profissional) profCtor.newInstance(nome, categoria);
// avoid duplicate nome in profissionalList
boolean isExist = false;
for(Profissional pro : profissionalList) {
if(pro != null){
if(pro.nome.toLowerCase().equals(newItem.nome.toLowerCase())){
isExist = true;
break;
}
}
}
if(!isExist){
profissionalList.add(newItem );
}
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissionalList) {
if(pro != null) {
System.out.println("nome: " + pro.nome + " categoria: " + pro.categoria);
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

How to reference class instances in Java methods for a basic text-based game inventory? [duplicate]

I have managed to put all objects into arraylist but I am not able to print all values. Only the last one is getting printed, regardless of method used.
It is not getting printed through ArrayList only, which makes me wonder if the objects pushed are the same. 
If it is, how do I change that? I have attached the program (run FileInput.java):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.swing.text.html.HTMLDocument.Iterator;
//lecture notes(L1) method
public class FileInput {
static String first;
static String second;
static String third;
static String fourth;
static String fifth;
static String sixth;
static int num = 1;
public static void main(String[] args)throws FileNotFoundException, IOException{
Scanner input = new Scanner(new File("player.txt"));
String data = null;
PrintWriter output = new PrintWriter("outfile.txt");
// Player1 user = new Player1();
ArrayList<Player1>listOfPlayers = new ArrayList<>();
Player1 user = new Player1();
// Tokenizing
System.out.println("CSCI213 Players Management System");
while(input.hasNextLine()){
System.out.println("\nPlayer " + num);
data = input.nextLine();
StringTokenizer token = new StringTokenizer(data,"|");
// int t = token.countTokens();
// System.out.println("t is:" + t);
first = token.nextToken().trim();
user.setLoginname(first);
second = new String(token.nextToken("|"));
user.setPassword(second);
third = new String(token.nextToken("|"));
user.setChips(third);
fourth = new String(token.nextToken("|"));
user.setUsername(fourth);
fifth = new String(token.nextToken("|"));
user.setEmail(fifth);
sixth = new String(token.nextToken("|"));
user.setBirthdate(sixth);
// user.display();
listOfPlayers.add(user);
System.out.println("Size is: " + listOfPlayers.size());
// System.out.println(user.loginname);
// System.out.println(listOfPlayers.get(num-1).loginname);
num++;
// output.write(data);
// output.write("\r\n");
}
int x = listOfPlayers.size();
System.out.println("Size is: " + x);
System.out.println(listOfPlayers);
// Display address of required
Player1 p = new Player1();
for(int i = 0; i < x; i++){
p = listOfPlayers.get(i);
System.out.println(p.loginname);
}
for(Player1 e:listOfPlayers){
System.out.println(e.loginname);
System.out.println(e.email);
}
while(input.hasNextLine()){
data = input.nextLine();
output.write(data);
output.write("\r\n");
}
input.close();
output.close();
}
}
// Store all player information
public class Player1 {
static String loginname;
static String password;
static String chips;
static String username;
static String email;
static String birthdate;
/*
public Player1(String loginname, String password,
String username, String email, String birthdate){
this.loginname = loginname;
this.password = password;
this.username = username;
this.email = email;
this.birthdate = birthdate;
}
*/
public Player1() {
// TODO Auto-generated constructor stub
}
public static String getLoginname() {
System.out.print("loginname: ");
return loginname;
}
public static void setLoginname(String loginname) {
Player1.loginname = loginname;
}
public static String getPassword() {
System.out.print("password: ");
return password;
}
public static void setPassword(String password) {
Player1.password = password;
}
public static String getUsername() {
System.out.print("username: ");
return username;
}
public static void setUsername(String username) {
Player1.username = username;
}
public static String getEmail() {
System.out.print("email: ");
return email;
}
public static void setEmail(String email) {
Player1.email = email;
}
public static String getBirthdate() {
System.out.print("birthdate: ");
return birthdate;
}
public static void setBirthdate(String birthdate) {
Player1.birthdate = birthdate;
}
public static String getChips() {
System.out.print("chips: ");
return chips;
}
public static void setChips(String chips) {
Player1.chips = chips;
}
public void display() {
System.out.println("Name: " + this.username);
System.out.println("Email: " + this.email);
System.out.println("Birthdate: " + this.birthdate);
System.out.println("Login ID: " + this.loginname);
System.out.println("Balance Chips: " + this.chips);
}
/*
#Override
public String toString() {
return "toString()=" + this.loginname + "\n";
}
*/
}
Simple:
Player1 user = new Player1();
You are adding the same object again and again. Put that statement into your loop instead. You want to add a completely new Playwer object during each loop iteration!
But even then, things wouldn't work out; because (as Eran figured): your Player class has only static fields. That is like "cheating"; because it means that all Player objects would see the same fields, too (because static fields are shared between all instances of a class!)
In other words: static is an abnormality in good OO design. You don't use it as default; to the contrary: you only make fields static in special corner cases (see here for some examples).
You have two errors :
You are adding the same Player1 instance to the list over and over again. You should move Player1 user = new Player1(); into the loop that adds the players.
Change
Player1 user = new Player1();
// Tokenizing
System.out.println("CSCI213 Players Management System");
while (input.hasNextLine()) {
to
// Tokenizing
System.out.println("CSCI213 Players Management System");
while (input.hasNextLine()) {
Player1 user = new Player1();
The members of the Player1 class are all static, so even if you fix the first issue, all instances of Player1 will share these members. You should change them to non static.
Change
public class Player1 {
static String loginname;
static String password;
static String chips;
static String username;
static String email;
static String birthdate;
to
public class Player1 {
String loginname;
String password;
String chips;
String username;
String email;
String birthdate;

AddressBook in Java

I have to create an address book in java. I have gotten stuck in one area. When I add a second address it makes the first one null. I have areas commented out that I haven't gotten to yet so ignore those areas. I am at a loss why the first address turns to null.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
class Program2 {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("\nWelcome. Address book is loaded.");
loop: while(true) {
displayOptions();
int choice = s.nextInt();
switch(choice) {
case 1:
System.out.println("**Choice 1**");
AddressBook.display();
break;
case 2:
System.out.println("**Choice 2**");
System.out.print("First Name: ");
String firstName = s.next();
System.out.print("Last Name: ");
String lastName = s.next();
System.out.print("Phone Number: ");
String phone = s.next();
Contact test = new Contact(firstName, lastName, phone);
AddressBook.add(test);
break;
case 3:
System.out.println("**Choice 3**");
break;
case 4:
System.out.println("**Choice 4**");
break;
case 5:
break loop;
}
}
System.out.println("\nAddress book is saved to file.\n");
System.out.println("Good bye.\n");
System.exit(0);
}
private static void displayOptions() {
System.out.println("\nWhat would you like to do?");
System.out.println(" 1) Display all contacts\n" +
" 2) Add a contact\n" +
" 3) Remove a contact\n" +
" 4) Search a contact\n" +
" 5) Exit");
System.out.print("Your choice: ");
}
}
class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getPhone() {return phone;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public void setPhone(String phone) {this.phone = phone;}
/*public boolean equals(Object o) {
if (o instanceof Contact) {
Contact contacts = (Contact) o;
return (firstName.equals(contacts.getFirstName()) &&
lastName.equals(contacts.getLastName()));
}
return false;
}*/
public String toString() {
return firstName + " " + lastName + "\t\t" + phone;
}
}
class AddressBook {
public final static int CAPACITY = 100;
static private Contact[] contacts;
static private int count = 0;
static private String addressFile = "address.txt";
static File file = new File(addressFile);
public AddressBook(String addressFile) {
this.addressFile = addressFile;
}
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY];
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
//public boolean remove(fullname) { }
//public Contact search(fullname) { }
public static void display() {
System.out.println("Name\t\t\tPhone Number");
System.out.println("-------------------------------------");
for (int i=0; i<count; i++) {
System.out.println(contacts[i]);
}
System.out.println("-------------------------------------");
}
/*public boolean load() {
try {
Scanner sF = new Scanner(file);
while (s.hasNext()) {
String line = s.nextLine();
System.out.println(line);
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*public boolean save() {
try {
FileWriter writer = new FileWriter(addressFile);
writer.write();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
//public boolean contains(String firstName, String lastName) {
// return this.contacts.contains(firstName, lastName);
//}
}
Your add method overwrites the contacts array, so each time it is called, the references to the previous Contacts are lost :
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY]; // remove this line
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
Instead of the removed line, initialize the contacts array only once :
static private Contact[] contacts = new Contact[CAPACITY];

Categories