Deleting a node in a family tree - java

I'm trying to calclulate the best way to delete a node in a family tree. First, a little description of how the app works.
My app makes the following assumption:
Any node can only have one partner. That means that any child a single node has, it will also be the partner nodes child too. Therefore, step relations, divorces etc aren't compensated for. A node always has two parents - A mother and father cannot be added seperately. If the user doesn't know the details - the nodes attributes are set to a default value.
Also any node can add parents, siblings, children to itself. Therefore in law relationships can be added.
EDIT: After studying Andreas' answer, I have come to realise that my code may need some re-working. I'm trying to add my source but it exceeds the limit of charracters...Any advice?
Here is the FamilyTree Class:
package familytree;
import java.io.PrintStream;
public class FamilyTree {
private static final int DISPLAY_FAMILY_MEMBERS = 1;
private static final int ADD_FAMILY_MEMBER = 2;
private static final int REMOVE_FAMILY_MEMBER = 3;
private static final int EDIT_FAMILY_MEMBER = 4;
private static final int SAVE_FAMILY_TREE = 5;
private static final int LOAD_FAMILY_TREE = 6;
private static final int DISPLAY_ANCESTORS = 7;
private static final int DISPLAY_DESCENDANTS = 8;
private static final int QUIT = 9;
private Input in;
private Family family;
private PrintStream out;
public FamilyTree(Input in, PrintStream out) {
this.in = in;
this.out = out;
family = new Family();
}
public void start() {
out.println("\nWelcome to the Family Tree Builder");
initialise();
while (true) {
displayFamilyTreeMenu();
int command = getCommand();
if (quit(command)) {
break;
}
executeOption(command);
}
}
private int getCommand() {
return getInteger("\nEnter command: ");
}
private int getInteger(String message) {
while (true) {
out.print(message);
if (in.hasNextInt()) {
int n = in.nextInt();
in.nextLine();
return n;
} else {
in.nextLine();
out.println("Your input was not understood. Please try again.");
}
}
}
//good
private void displayFamilyTreeMenu() {
out.println("\nFamily Tree Menu");
out.println(DISPLAY_FAMILY_MEMBERS + ". Display Family Members");
out.println(ADD_FAMILY_MEMBER + ". Add Family Member");
out.println(REMOVE_FAMILY_MEMBER + ". Remove Family Member");
out.println(EDIT_FAMILY_MEMBER + ". Edit Family Member");
out.println(SAVE_FAMILY_TREE + ". Save Family Tree");
out.println(LOAD_FAMILY_TREE + ". Load Family Tree");
out.println(DISPLAY_ANCESTORS + ". Display Ancestors");
out.println(DISPLAY_DESCENDANTS + ". Display Descendants");
out.println(QUIT + ". Quit");
}
//good
private boolean quit(int opt) {
return (opt == QUIT) ? true : false;
}
//good
private void executeOption(int choice) {
switch (choice) {
case DISPLAY_FAMILY_MEMBERS:
displayFamilyMembers();
break;
case ADD_FAMILY_MEMBER:
addFamilyMember();
break;
case REMOVE_FAMILY_MEMBER:
removeMember();
break;
case EDIT_FAMILY_MEMBER:
editMember();
break;
case SAVE_FAMILY_TREE:
saveFamilyTree();
break;
case LOAD_FAMILY_TREE:
loadFamilyTree();
break;
case DISPLAY_ANCESTORS:
displayAncestors();
break;
case DISPLAY_DESCENDANTS:
displayDescendants();
break;
default:
out.println("Not a valid option! Try again.");
break;
}
}
private void removeMember() {
displayFamilyMembers();
int choice = selectMember();
if (choice >= 0) {
FamilyMember f = family.getFamilyMember(choice);
if (f.getIndex() == 0) {
out.println("Cannot delete yourself!");
return;
}
deleteMember(f);
}
}
private void deleteMember(FamilyMember f) {
//remove from tree
family.removeMember(f);
//remove all links to this person
if (f.hasParents()) {
f.getMother().removeChild(f);
f.getFather().removeChild(f);
}
if(f.getPartner()!=null){
f.getPartner().setPartner(null);
f.setPartner(null);
}
if (f.hasChildren()) {
for (FamilyMember member : f.getChildren()) {
if (f == member.getMother()) {
member.setMother(null);
}
if (f == member.getFather()) {
member.setFather(null);
}
if (f == member.getPartner()) {
member.setPartner(null);
}
}
}
}
private void saveFamilyTree() {
out.print("Enter file name: ");
String fileName = in.nextLine();
FileOutput output = new FileOutput(fileName);
family.save(output);
output.close();
saveRelationships();
}
private void saveRelationships() {
FileOutput output = new FileOutput("Relationships.txt");
family.saveRelationships(output);
output.close();
}
private void loadFamilyTree() {
out.print("Enter file name: ");
String fileName = in.nextLine();
FileInput input = new FileInput(fileName);
family.load(input);
input.close();
loadRelationships();
}
private void loadRelationships() {
FileInput input = new FileInput("Relationships.txt");
family.loadRelationships(input);
input.close();
}
//for selecting family member for editing adding nodes etc
private void displayFamilyMembers() {
out.println("\nDisplay Family Members");
int count = 0;
for (FamilyMember member : family.getFamilyMembers()) {
out.println();
if (count + 1 < 10) {
out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName());
out.println(" " + member.getGender());
out.println(" " + member.getDob());
out.println(" Generation: " + (member.getGeneration() + 1));
} else {
out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName());
out.println(" " + member.getGender());
out.println(" " + member.getDob());
out.println(" Generation: " + (member.getGeneration() + 1));
}
count++;
}
}
private int selectRelative() {
out.println("\nSelect Relative");
out.println("1. Add Parents");
out.println("2. Add Child");
out.println("3. Add Partner");
out.println("4. Add Sibling");
//out.print("\nEnter Choice: ");
//int choice = in.nextInt();
int choice = getInteger("\nEnter Choice: ");
if (choice > 0 && choice < 5) {
return choice;
}
return (-1);
}
private void addFamilyMember() {
if (family.getFamilyMembers().isEmpty()) {
out.println("No Members To Add To");
return;
}
int memberIndex = selectMember();
if (memberIndex >= 0) {
FamilyMember member = family.getFamilyMember(memberIndex);
int relative = selectRelative();
if (relative > 0) {
out.println("\nAdd Member");
//if choice is valid
switch (relative) {
case 1:
//adding parents
FamilyMember mum, dad;
if (!member.hasParents()) {
out.println("Enter Mothers Details");
mum = addMember(relative, "Female");
out.println("\nEnter Fathers Details");
dad = addMember(relative, "Male");
member.linkParent(mum);
member.linkParent(dad);
mum.linkPartner(dad);
mum.setGeneration(member.getGeneration() - 1);
dad.setGeneration(member.getGeneration() - 1);
sortGenerations();
} else {
out.println(member.getFirstName() + " " + member.getLastName() + " already has parents.");
}
break;
case 2:
//adding child
if (member.getPartner() == null) {
FamilyMember partner;
if (member.getGender().equals("Male")) {
out.println("Enter Mothers Details");
partner = addMember(1, "Female");
} else {
out.println("Enter Fathers Details");
partner = addMember(1, "Male");
}
//create partner
member.linkPartner(partner);
partner.setGeneration(member.getGeneration());
out.println();
}
out.println("Enter Childs Details");
FamilyMember child = addMember(relative, "");
child.linkParent(member);
child.linkParent(member.getPartner());
child.setGeneration(member.getGeneration() + 1);
sortGenerations();
break;
case 3:
//adding partner
if (member.getPartner() == null) {
out.println("Enter Partners Details");
FamilyMember partner = addMember(relative, "");
member.linkPartner(partner);
partner.setGeneration(member.getGeneration());
} else {
out.println(member.getFirstName() + " " + member.getLastName() + " already has a partner.");
}
break;
case 4:
//adding sibling
if (member.getFather() == null) {
out.println("Enter Mothers Details");
mum = addMember(1, "Female");
out.println("\nEnter Fathers Details");
dad = addMember(1, "Male");
member.linkParent(mum);
member.linkParent(dad);
mum.linkPartner(dad);
mum.setGeneration(member.getGeneration() - 1);
dad.setGeneration(member.getGeneration() - 1);
sortGenerations();
out.println("\nEnter Siblings Details");
} else {
out.println("Enter Siblings Details");
}
FamilyMember sibling = addMember(relative, "");
//create mum and dad
mum = member.getMother();
dad = member.getFather();
sibling.linkParent(mum);
sibling.linkParent(dad);
sibling.setGeneration(member.getGeneration());
break;
}
} else {
out.println("Invalid Option!");
}
} else {
out.println("Invalid Option!");
}
}
private int selectMember() {
displayFamilyMembers();
//out.print("\nSelect Member: ");
//int choice = in.nextInt();
int choice = getInteger("\nSelect Member: ");
if (choice > 0 && choice <= family.getFamilyMembers().size()) {
return (choice - 1);
}
return -1;
}
private void editMember() {
int choice = selectMember();
if (choice >= 0) {
out.println("Select Detail To Edit: ");
out.println("1. Name");
out.println("2. Gender");
out.println("3. Date of Birth");
//out.print("\nEnter Choice: ");
//int opt = in.nextInt();
int opt = getInteger("\nEnter Choice: ");
if (opt > 0 && opt < 4) {
switch (opt) {
case 1: //name
out.print("Enter New First Name: ");
String fName = in.nextLine();
out.print("Enter New Last Name: ");
String lName = in.nextLine();
family.changeName(fName, lName, choice);
break;
case 2: //Gender
FamilyMember f = family.getFamilyMember(choice);
String gender = f.getGender();
if (f.getChildren().isEmpty()) {
gender = selectGender();
family.changeGender(gender, choice);
} else {
//swap genders
//swap mother father relationships for kids
swapGenders(f, choice);
}
break;
case 3:
String dob = enterDateOfBirth();
family.changeDOB(dob, choice);
}
} else {
out.println("Invalid Choice!");
}
}
}
private FamilyMember addMember(int option, String gender) {
out.print("Enter First Name: ");
String fName = formatString(in.nextLine().trim());
out.print("Enter Last Name: ");
String lName = formatString(in.nextLine().trim());
//String gender;
if (option != 1) { //if not adding parents
gender = selectGender();
}
String dob = enterDateOfBirth();
FamilyMember f = family.getFamilyMember(family.addMember(fName, lName, gender, dob));
f.setIndex(family.getFamilyMembers().size() - 1);
return (f);
}
private String selectGender() {
String gender = null;
out.println("Select Gender");
out.println("1. Male");
out.println("2. Female");
//out.print("Enter Choice: ");
//int gOpt = in.nextInt();
int gOpt = getInteger("Enter Choice: ");
if (gOpt == 1) {
gender = "Male";
} else if (gOpt == 2) {
gender = "Female";
} else {
out.println("Invalid Choice");
}
return gender;
}
private void swapGenders(FamilyMember f, int choice) {
String gender;
out.println("\nNOTE: Editing A Parent Nodes Gender Will Swap Parents Genders\n"
+ "And Swap Mother/Father Relationships For All Children.");
out.println("\nContinue:");
out.println("1. Yes");
out.println("2. No");
//out.print("\nEnter Choice: ");
//int select = in.nextInt();
int select = getInteger("\nEnter Choice: ");
if (select > 0 && select < 3) {
switch (select) {
case 1:
//swap relationships
gender = selectGender();
//if selected gender is different
if (!gender.equals(f.getGender())) {
//swap
String g = f.getGender();
family.changeGender(gender, choice);
family.changeGender(g, f.getPartner().getIndex());
if (g.equals("Male")) {
for (FamilyMember m : f.getChildren()) {
m.setMother(f);
m.setFather(f.getPartner());
}
} else {
for (FamilyMember m : f.getChildren()) {
m.setFather(f);
m.setMother(f.getPartner());
}
}
}
break;
case 2:
break;
}
} else {
out.println("Invalid Choice");
}
}
private String formatString(String s) {
String firstLetter = s.substring(0, 1);
String remainingLetters = s.substring(1, s.length());
s = firstLetter.toUpperCase() + remainingLetters.toLowerCase();
return s;
}
private String enterDateOfBirth() {
out.print("Enter Year Of Birth (0 - 2011): ");
String y = in.nextLine();
out.print("Enter Month Of Birth (1-12): ");
String m = in.nextLine();
if (m.trim().equals("")) {
m = "0";
}
if (Integer.parseInt(m) < 10) {
m = "0" + m;
}
m += "-";
out.print("Enter Date of Birth (1-31): ");
String d = in.nextLine();
if (d.trim().equals("")) {
d = "0";
}
if (Integer.parseInt(d) < 10) {
d = "0" + d;
}
d += "-";
String dob = d + m + y;
while (!DateValidator.isValid(dob)) {
out.println("Invalid Date. Try Again:");
dob = enterDateOfBirth();
}
return (dob);
}
private void displayAncestors() {
out.print("\nDisplay Ancestors For Which Member: ");
int choice = selectMember();
if (choice >= 0) {
FamilyMember node = family.getFamilyMember(choice);
FamilyMember ms = findRootNode(node, 0, 2, -1);
FamilyMember fs = findRootNode(node, 1, 2, -1);
out.println("\nPrint Ancestors");
out.println("\nMothers Side");
if(ms==null){
out.println("Member has no mother");
}else{
printDescendants(ms, node, ms.getGeneration());
}
out.println("\nFathers Side");
if(fs==null){
out.println("Member has no father");
}else{
printDescendants(fs, node, fs.getGeneration());
}
} else {
out.println("Invalid Option!");
}
}
private void displayDescendants() {
out.print("\nDisplay Descendants For Which Member: ");
int choice = selectMember();
if (choice >= 0) {
FamilyMember node = family.getFamilyMember(choice);
out.println("\nPrint Descendants");
printDescendants(node, null, 0);
} else {
out.println("Invalid Option!");
}
}
private FamilyMember findRootNode(FamilyMember node, int parent, int numGenerations, int count) {
FamilyMember root;
count++;
if (count < numGenerations) {
if (parent == 0) {
if(node.hasMother()){
node = node.getMother();
}else{
return node;
}
} else {
if(node.hasFather()){
node = node.getFather();
}else{
return node;
}
}
root = findRootNode(node, 1, numGenerations, count);
return root;
}
return node;
}
private int findHighestLeafGeneration(FamilyMember node) {
int gen = node.getGeneration();
for (int i = 0; i < node.getChildren().size(); i++) {
int highestChild = findHighestLeafGeneration(node.getChild(i));
if (highestChild > gen) {
gen = highestChild;
}
}
return gen;
}
private void printDescendants(FamilyMember root, FamilyMember node, int gen) {
out.print((root.getGeneration() + 1) + " " + root.getFullName());
out.print(" [" + root.getDob() + "] ");
if (root.getPartner() != null) {
out.print("+Partner: " + root.getPartner().getFullName() + " [" + root.getPartner().getDob() + "] ");
}
if (root == node) {
out.print("*");
}
out.println();
if (!root.getChildren().isEmpty() && root != node) {
for (int i = 0; i < root.getChildren().size(); i++) {
for (int j = 0; j < root.getChild(i).getGeneration() - gen; j++) {
out.print(" ");
}
printDescendants(root.getChild(i), node, gen);
}
} else {
return;
}
}
//retrieve highest generation
public int getRootGeneration() {
int min = family.getFamilyMember(0).getGeneration();
for (int i = 0; i < family.getFamilyMembers().size(); i++) {
min = Math.min(min, family.getFamilyMember(i).getGeneration());
}
return Math.abs(min);
}
public void sortGenerations() {
int amount = getRootGeneration();
for (FamilyMember member : family.getFamilyMembers()) {
member.setGeneration(member.getGeneration() + amount);
}
}
//test method - temporary
private void initialise() {
family.addMember("Bart", "Simpson", "Male", "18-03-1985");
family.getFamilyMember(0).setIndex(0);
family.addMember("Homer", "Simpson", "Male", "24-09-1957");
family.getFamilyMember(1).setIndex(1);
family.addMember("Marge", "Simpson", "Female", "20-07-1960");
family.getFamilyMember(2).setIndex(2);
family.addMember("Lisa", "Simpson", "Female", "28-01-1991");
family.getFamilyMember(3).setIndex(3);
family.addMember("Abe", "Simpson", "Male", "10-03-1920");
family.getFamilyMember(4).setIndex(4);
family.addMember("Mona", "Simpson", "Female", "18-09-1921");
family.getFamilyMember(5).setIndex(5);
//set relationships
family.getFamilyMember(0).setMother(family.getFamilyMember(2));
family.getFamilyMember(0).setFather(family.getFamilyMember(1));
family.getFamilyMember(3).setMother(family.getFamilyMember(2));
family.getFamilyMember(3).setFather(family.getFamilyMember(1));
family.getFamilyMember(1).addChild(family.getFamilyMember(3));
family.getFamilyMember(1).addChild(family.getFamilyMember(0));
family.getFamilyMember(2).addChild(family.getFamilyMember(3));
family.getFamilyMember(2).addChild(family.getFamilyMember(0));
family.getFamilyMember(1).setPartner(family.getFamilyMember(2));
family.getFamilyMember(2).setPartner(family.getFamilyMember(1));
family.getFamilyMember(4).setPartner(family.getFamilyMember(5));
family.getFamilyMember(5).setPartner(family.getFamilyMember(4));
family.getFamilyMember(1).setMother(family.getFamilyMember(5));
family.getFamilyMember(1).setFather(family.getFamilyMember(4));
family.getFamilyMember(4).addChild(family.getFamilyMember(1));
family.getFamilyMember(5).addChild(family.getFamilyMember(1));
family.getFamilyMember(0).setGeneration(2);
family.getFamilyMember(1).setGeneration(1);
family.getFamilyMember(2).setGeneration(1);
family.getFamilyMember(3).setGeneration(2);
family.getFamilyMember(4).setGeneration(0);
family.getFamilyMember(5).setGeneration(0);
}
}

All tasks require the same effort. It will always go like this:
public void deleteFamilyMember(FamilyMember member) {
member.mother.children.remove(member);
member.father.children.remove(member);
member.partner.children.remove(member);
for (FamilyMember child:children) {
if (child.father == member) child.father = null;
if (child.mother == member) child.mother = null;
if (child.partner == member) child.partner = null;
}
// now all references to this member are eliminated, gc will do the rest.
}
Example:
Homer.mother = ??
Homer.father = ??
Homer.partner = Marge
Homer.children = {Bart, Lisa, Maggie}
Marge.mother = ??
Marge.father = ??
Marge.partner = Homer
Marge.children = {Bart, Lisa, Maggie}
Bart.mother = Marge
Bart.father = Homer
Bart.partner = null
Bart.children = {}
Lisa.mother = Marge
Lisa.father = Homer
Lisa.partner = null
Lisa.children = {}
Maggie.mother = Marge
Maggie.father = Homer
Maggie.partner = null
Maggie.children = {}
To remove Bart from the familiy tree, we should set Bart's mother and father attribute to null and need to remove Bart from Homer's and Marge's list of children.
To remove Marge, we have to set her partner's partner to null (Homer.partner) and visit all children to clear their mother attribute (that's this child.mother part of the code above)

I would model things differently and do the work in the FamilyMember class. Here's a sample implementation:
public class FamilyMember{
public enum Gender{
MALE, FEMALE
}
private final Set<FamilyMember> exPartners =
new LinkedHashSet<FamilyMember>();
public Set<FamilyMember> getExPartners(){
return new LinkedHashSet<FamilyMember>(exPartners);
}
public FamilyMember getFather(){
return father;
}
public FamilyMember getMother(){
return mother;
}
public Set<FamilyMember> getSiblings(){
final Set<FamilyMember> set =
father == null && mother == null ? Collections
.<FamilyMember> emptySet() : new HashSet<FamilyMember>();
if(father != null){
set.addAll(father.children);
}
if(mother != null){
set.addAll(mother.children);
}
set.remove(this);
return set;
}
public String getName(){
return name;
}
private final Gender gender;
private FamilyMember partner;
private final FamilyMember father;
private final FamilyMember mother;
private final Set<FamilyMember> children =
new LinkedHashSet<FamilyMember>();
private final String name;
public FamilyMember haveChild(final String name, final Gender gender){
if(partner == null){
throw new IllegalStateException("Partner needed");
}
final FamilyMember father = gender == Gender.MALE ? this : partner;
final FamilyMember mother = father == this ? partner : this;
return new FamilyMember(father, mother, name, gender);
}
public Set<FamilyMember> getChildren(){
return new LinkedHashSet<FamilyMember>(children);
}
#Override
public String toString(){
return "[" + name + ", " + gender + "]";
}
public FamilyMember(final String name, final Gender gender){
this(null, null, name, gender);
}
public FamilyMember(final FamilyMember father,
final FamilyMember mother,
final String name,
final Gender gender){
if(name == null){
throw new IllegalArgumentException("A kid needs a name!");
}
if(gender == null){
throw new IllegalArgumentException("Which is it going to be?");
}
this.father = father;
this.name = name;
this.gender = gender;
if(father != null){
father.children.add(this);
}
this.mother = mother;
if(mother != null){
mother.children.add(this);
}
}
public FamilyMember hookUpWith(final FamilyMember partner){
if(partner.gender == gender){
throw new IllegalArgumentException(
"Sorry, same-sex-marriage would make things too complicated");
}
this.partner = partner;
partner.partner = this;
return this;
}
public FamilyMember splitUp(){
if(partner == null){
throw new IllegalArgumentException("Hey, I don't have a partner");
} else{
partner.partner = null;
exPartners.add(partner);
partner.exPartners.add(this);
partner = null;
}
return this;
}
public FamilyMember getPartner(){
return partner;
}
}
And here's the much more expressive code you can write that way:
FamilyMember marge = new FamilyMember("Marge", Gender.FEMALE);
FamilyMember homer = new FamilyMember("Homer", Gender.MALE);
homer.hookUpWith(marge);
FamilyMember bart = homer.haveChild("Bart", Gender.MALE);
FamilyMember lisa = marge.haveChild("Lisa", Gender.FEMALE);
System.out.println("Homer & Marge: " + marge + ", "
+ marge.getPartner());
homer.splitUp();
FamilyMember dolores =
marge
.hookUpWith(new FamilyMember("New Guy", Gender.MALE))
.haveChild("Dolores", Gender.FEMALE);
FamilyMember bruno =
homer
.hookUpWith(new FamilyMember("New Girl", Gender.FEMALE))
.haveChild("Bruno", Gender.MALE);
System.out.println(
"Marge & Partner: " + marge + ", " + marge.getPartner());
System.out.println("Marge's Ex-Partners: " + marge.getExPartners());
System.out.println(
"Homer & Partner: " + homer + ", " + homer.getPartner());
System.out.println("Homer's Ex-Partners: " + homer.getExPartners());
System.out.println("Marge's kids: " + marge.getChildren());
System.out.println("Homer's kids: " + homer.getChildren());
System.out.println("Dolores's siblings: " + dolores.getSiblings());
System.out.println("Brunos's siblings: " + bruno.getSiblings());
Output:
Homer & Marge: [Marge, FEMALE], [Homer, MALE]
Marge & Partner: [Marge, FEMALE], [New Guy, MALE]
Marge's Ex-Partners: [[Homer, MALE]]
Homer & Partner: [Homer, MALE], [New Girl, FEMALE]
Homer's Ex-Partners: [[Marge, FEMALE]]
Marge's kids: [[Bart, MALE], [Lisa, FEMALE], [Dolores, FEMALE]]
Homer's kids: [[Bart, MALE], [Lisa, FEMALE], [Bruno, MALE]]
Dolores's siblings: [[Bart, MALE], [Lisa, FEMALE]]
Brunos's siblings: [[Bart, MALE], [Lisa, FEMALE]]

Related

purchase management program that shows error on specific inputs in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
The code works on a linkedlist principle, and has worked alright thus far, however the code outputs an error when input is add, 1, a, 10, 5, add, 1, b, 2, 2, add, 2, b, 2, 1, inc, 2, b, print, done
the code:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;
class Prece {
private String nosaukums;
private double cena;
private int daudzums;
public Prece(String n, double c, int d) {
nosaukums = n;
cena = c;
daudzums = d;
}
public String getNosaukums() {
return nosaukums;
}
public double getCena() {
return cena;
}
public int getDaudzums() {
return daudzums;
}
public void setDaudzums(int d) {
daudzums = d;
}
public static Prece inputPrece(Scanner sc) {
String n = sc.next();
double c = sc.nextDouble();
int d = sc.nextInt();
return new Prece(n, c, d);
}
public void outputPrece() {
System.out.printf("%-20s%-10.2f%-10d\n", nosaukums, cena, daudzums);
}
}
public class Main {
public static Scanner sc;
public static void main(String[] args) {
HashMap<String, LinkedList<Prece>> pasutijumi = new HashMap<String, LinkedList<Prece>>();
sc = new Scanner(System.in);
String cmd = "";
while (!cmd.equals("done")) {
cmd = sc.next();
switch (cmd) {
case "add":
add(pasutijumi);
break;
case "print":
print(pasutijumi);
break;
case "sum":
sum(pasutijumi);
break;
case "inc":
inc(pasutijumi);
break;
case "del":
delete(pasutijumi);
break;
case "done":
System.out.println("good bye");
break;
default:
System.out.println("unknown command");
break;
}
}
sc.close();
}
public static void print(HashMap<String, LinkedList<Prece>> pasutijumi) {
LinkedList<Prece> grozs;
for (String id : pasutijumi.keySet()) {
System.out.println("ID: " + id);
grozs = pasutijumi.get(id);
String str = String.format("%-20s%-10s%-10s", "nosaukums", "cena", "daudzums");
System.out.println(str);
for (Prece prece : grozs) {
prece.outputPrece();
}
}
}
public static void inc(HashMap<String, LinkedList<Prece>> pasutijumi) {
String id = sc.next();
String productName = sc.next();
double amount = sc.nextDouble();
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs == null) {
System.out.println("unknown client");
} else {
boolean productFound = false;
for (Prece prece : grozs) {
if (prece.getNosaukums().equals(productName)) {
prece.setDaudzums(prece.getDaudzums() + (int) amount);
productFound = true;
break;
}
}
if (!productFound) {
System.out.println("not found");
}
}
}
public static void add(HashMap<String, LinkedList<Prece>> pasutijumi) {
LinkedList<Prece> grozs;
String id = sc.next();
Prece p = Prece.inputPrece(sc);
grozs = pasutijumi.get(id);
if (grozs != null) {
grozs.add(p);
} else {
grozs = new LinkedList<Prece>();
grozs.add(p);
pasutijumi.put(id, grozs);
}
}
public static void sum(HashMap<String, LinkedList<Prece>> pasutijumi) {
for (String id : pasutijumi.keySet()) {
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs != null) {
double sum = 0.0;
for (Prece prece : grozs) {
sum += prece.getCena() * prece.getDaudzums();
}
System.out.println("ID: " + id + " sum: " + sum);
} else {
System.out.println("unknown client");
}
}
}
public static void delete(HashMap<String, LinkedList<Prece>> pasutijumi) {
String id = sc.next();
String nosaukums = sc.next();
LinkedList<Prece> grozs = pasutijumi.get(id);
if (grozs != null) {
int index = -1;
for (int i = 0; i < grozs.size(); i++) {
if (grozs.get(i).getNosaukums().equals(nosaukums)) {
index = i;
break;
}
}
if (index >= 0) {
Prece prece = grozs.remove(index);
System.out.println("Prece " + prece.getNosaukums() + " noņemta no klienta ar ID " + id + " pasūtījuma");
} else {
System.out.println("Prece " + nosaukums + " nav atrasta klienta ar ID " + id + " pasūtījumā");
}
} else {
System.out.println("Klienta ID " + id + " nav atrasts");
}
}
}
Sorry that the code is in latvian.
I have tried changing the list types and tried bug fixing however it still shows an error.

How to read values from array list from another class and get output depending on user input?

So, I'm trying to figure out how to get values of an array list from another class and print certain values depending on user input.
For example, firstly a user is asked to provide a location, once they enter a location, it has to read the user input and output the results according to the location.an image is provided about the output.
For some reason it doesn't output the correct values from array list.
Could you please help me out?
This is my code for reading values from array list.
public class Program {
ArrayList<Properties> property = Properties.getMelbnbProperty();
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
ArrayList<Properties> output = Properties.getMelbnbProperty();
if(Properties.getMelbnbProperty().contains(choice)) {
output.addAll(Properties.getMelbnbProperty());
}
} }
This is my code for array list.
public class Properties {
public static ArrayList<Properties> getMelbnbProperty() {
// Below is an arraylist where I have stored the Melbnb data
ArrayList<Properties> property = new ArrayList<Properties>();
property.add(new Properties("Private room in the heart of Southbank"));
property.add(new Properties("Spacious bedroom in a cosy apartment in South Yarra\n"));
property.add(new Properties("Ensuite room with great views"));
property.add(new Properties("Single room next to Carlton Gardens"));
property.add(new Properties("Studio close to Melbourne CBD"));
property.add(new Properties("1-bedroom CBD view suite near Melbourne Central and RMIT"));
property.add(new Properties("Stylish two bedroom in CBD"));
property.add(new Properties("Sky high studio with amazing views"));
property.add(new Properties("Budget accommodation bunk beds"));
property.add(new Properties("A beautiful room near Marvel Stadium"));
return property;
}}
The code you have provided in your question post is incomplete and in a way doesn't make sense to what your image displays. I do however understand what you are trying to accomplish but the way I see it your properties class is somewhat under-nourished.
I don't know if this is the intentional purpose but your for loop:
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
is designed to pull out 1 object from the property ArrayList. This loop is completely unnecessary since just supplying an index value of 1 to the ArrayList#get() method does exactly the same thing and is only a single line of code, for example:
System.out.println(property.get(1));
I say this because your for loop initializer starts at index 1, there is no iterator for the loop, and you apply the break statement directly after the display of the object within the ArrayList.
To access all elements within the ArrayList (your post indicates) you would need to do something like this:
for (int i = 0; i < properties.size(); i++) {
System.out.println(properties.get(i));
}
Or you can use:
for (String props: properties) {
System.out.println(props);
}
To be honest, what you are showing for code in grossly underdeveloped. I don't want to come across as insulting but it's obvious that you are not showing as much as you should be and therefore it is extremely difficult to provide you with any concrete solution to your problem. For this reason, I think it is just easier to provide you with a working demo console application which would allow you to perhaps grasp some concepts from.
The runnable code below consists of two specific classes, the start up class named SimpleBNBDemo which contains the main() method and the Properties class which allows you to instantiate instances of different BNB properties. As you can see, the Properties class is somewhat more fulfilled than the class you provided in your question post. Take the time to read through the code and try to follow its flow. Do keep in mind, although runnable this is only a Demo application and is in now way a complete works. I personally would never hard-code fill an ArrayList with Object data. This data should come from and or saved to a file system or database. However, for demo purposes this will suffice.
The SimpleBNBDemo class:
public class SimpleBNBDemo {
// Field variables
public final static String LS = System.lineSeparator();
public final static java.util.Scanner USER_INPUT = new java.util.Scanner(System.in);
// class member variable
private Properties prop = new Properties();
private final String line = "------------------------------------------------";
private int pwAttempts = 0;
public static void main(String[] args) {
// Started this way to avoid the need for statics
new SimpleBNBDemo().startApp(args);
}
private void startApp(String[] args) {
/* Create Properties instances...
You can do this with whatever means you like. */
java.util.List<Properties> properties = prop.getProperties();
properties.add(new Properties("Southbank Mannor", "Room", "Private room in the heart of Southbank.", "South", 86.00d, true));
properties.add(new Properties("Yarra House", "Room", "Spacious bedroom in a cosy apartment in South Yarra.", "South", 74.00d, true));
properties.add(new Properties("Ensuite Haven", "Room", "Ensuite room with great views.", "West", 65.50d, true));
properties.add(new Properties("Carlton Place", "Room", "Single room next to Carlton Gardens.", "South", 78.00d, true));
properties.add(new Properties("Melbourne Studio", "Studio", "Studio close to Melbourne CBD.", "East", 78.00d, true));
properties.add(new Properties("Melbourne Delight", "Room", "1-bedroom CBD view suite near Melbourne Central and RMIT.", "North", 135.00d, true));
properties.add(new Properties("CBD House", "Suit", "Stylish two bedroom in CBD.", "West", 100.00d, true));
properties.add(new Properties("Sky-High", "Studio", "Sky high studio with amazing views.", "North", 95.00d, true));
properties.add(new Properties("Budgeteer", "Room", "Budget accommodation bunk beds.", "South", 65.00d, true));
properties.add(new Properties("Stadium House", "Room", "A beautiful room near Marvel Stadium.", "East", 95.00d, true));
println("Welcome to MelBNB" + LS + line);
println();
// Menu 1 - Main Menu
String choice = "";
String[] locations = prop.getAllLocations();
if (locations.length == 0) {
printErr("No BNB's with Location in database yet!");
return;
}
while (choice.isEmpty()) {
println("Select from Main Menu:");
println(" 1) List all Accomodations");
println(" 2) Search by location");
println(" 3) Browse by type of accomodation");
println(" 4) Filter by rating");
println(" 5) Rate an accomodation");
println(" 6) Exit (quit)");
print("Please choose: -> ");
choice = USER_INPUT.nextLine().trim();
// Validate Entry...switch/case works great for input validation.
switch (choice) {
case "1":
listAllAccomodations();
break;
case "2":
searchByLocation();
break;
case "3":
searchByAccomodationType();
break;
case "4":
searchByRating();
break;
case "5":
rateAnAccomodation();
break;
case "6":
break;
case "~admin~":
adminMenu();
break;
case "~admin attempts reset~":
pwAttempts = 0;
println();
break;
default:
println("Invalid Entry (" + choice + ")! Try again..." + LS);
}
// Was 'Exit' (4) selected?
if (choice.equals("6")) {
// Break out of loop to end application.
println(LS + "Thank you for visiting MelBNB, Bye-Bye." + LS);
break;
}
choice = ""; // Reset 'choice' to be empty in order to loop again..
}
}
private void adminMenu() {
String pwrd = "";
while (pwrd.isEmpty()) {
if (pwAttempts >= 3) {
println(LS + "Admin Menu is NOT Available!" + LS + "To many failed "
+ "consecutive password attempts!" + LS + "Only " + pwAttempts
+ " consecutive attempts are allowed." + LS);
return;
}
print(LS + "Please enter Admin Password (c to cancel): --> ");
pwrd = USER_INPUT.nextLine().trim();
if (pwrd.equalsIgnoreCase("c")) {
println();
return;
}
int psum = 0;
for (int i = 0; i < pwrd.length(); i++) {
psum += pwrd.charAt(i);
}
if (psum != 624) {
pwAttempts++;
println("Invalid Password! Try again...");
pwrd = "";
}
}
pwAttempts = 0;
println();
println("***********************************************");
println("*** Administrative options would go here! ***");
println("*** Press Enter To Continue ***");
println("***********************************************");
String nothing = USER_INPUT.nextLine().trim();
}
private void listAllAccomodations() {
println(LS + "All Available Accomodations:");
println("----------------------------");
int cntr = 0;
String underline = "";
for (Properties pp : prop.getProperties()) {
cntr++;
String str = pp.toStringTable(pp, cntr == 1);
underline = String.join("", java.util.Collections.nCopies(str.length(), "="));
println(str);
if (cntr == 15) {
println("<- Press Enter To Continue ->");
String nuthin = USER_INPUT.nextLine().trim();
cntr = 0;
}
}
println(underline + LS);
}
private void searchByLocation() {
String[] locationTypes = prop.getAllLocations();
java.util.Arrays.sort(locationTypes);
String locationChoice = "";
while (locationChoice.isEmpty()) {
println();
println("Select the desired location:");
int i = 0;
for ( ; i < locationTypes.length; i++) {
println(" " + (i + 1) + ") " + locationTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
locationChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!locationChoice.matches("[1-" + (locationTypes.length + 1) + "]")) {
println("Invalid Entry (" + locationChoice + ")! Try again..." + LS);
locationChoice = "";
}
}
if (locationChoice.equals(String.valueOf(locationTypes.length + 1))) {
println();
return;
}
String location = locationTypes[Integer.valueOf(locationChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByLocation(location);
if (p.isEmpty()) {
println("No accomodations available in the " + location + " area!" + LS);
return;
}
String str = "Available accomodation within the " + location + " area:";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByAccomodationType() {
String[] accTypes = prop.getAllAccomodationTypes();
java.util.Arrays.sort(accTypes);
String accChoice = "";
while (accChoice.isEmpty()) {
println();
println("Select the desired accomodation type:");
int i = 0;
for ( ; i < accTypes.length; i++) {
println(" " + (i + 1) + ") " + accTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
accChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!accChoice.matches("[1-" + (accTypes.length + 1) + "]")) {
println("Invalid Entry (" + accChoice + ")! Try again..." + LS);
accChoice = "";
}
}
if (accChoice.equals(String.valueOf(accTypes.length + 1))) {
println();
return;
}
String acc = accTypes[Integer.valueOf(accChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByAccomodationType(acc);
if (p.isEmpty()) {
println("No accomodation type of " + acc + " is available!" + LS);
return;
}
String str = "Available accomodation that are of type '" + acc + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByRating() {
String rateChoice = "";
while (rateChoice.isEmpty()) {
println();
println("Enter the desired accomodation rating (1 to 5);");
print( "Enter c to cancel. Desired Rating: --> ");
rateChoice = USER_INPUT.nextLine().trim();
if (rateChoice.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateChoice.matches("[1-5]")) {
println("Invalid Entry (" + rateChoice + ")! Try again..." + LS);
rateChoice = "";
}
}
int rating = Integer.valueOf(rateChoice);
java.util.List<Properties> p = prop.getPropertiesByRating(rating);
if (p.isEmpty()) {
println("No accomodation available with the rating of " + rating + "!" + LS);
return;
}
String str = "Available accomodation with a rating of '" + rating + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void rateAnAccomodation() {
/* Displayed ratings are always the AVERAGE of all ratings
provided for that particular propety. This is done within
the 'Properties.addRating()' method. For this reason and
for other obvious reasons the Properties List should be
saved to either a file or a database. If this is not done
then all added or modified data will be lost when the
application closes. The Properties List data should NOT
be hard-coded. It should be loaded in when the application
starts and saved to storage when data is added or modified.
*/
String[] pNames = prop.getAllPropertyNames();
String nameToRate = "";
while (nameToRate.isEmpty()) {
println(LS + "Enter the name of the accomodation you want to rate:");
print( "Enter 'c' to cancel. Rating: --> ");
nameToRate = USER_INPUT.nextLine().trim();
if (nameToRate.equalsIgnoreCase("c")) {
return;
}
// Validate Entry............................
if (nameToRate.isEmpty()) {
println("Invalid Entry! You must enter a Name! Try again...");
nameToRate = "";
continue;
}
// Does the name exist in List?
boolean found = false;
for (String name : pNames) {
if (name.equalsIgnoreCase(nameToRate)) {
// Yes it does...
found = true;
break; // Break out of this loop.
}
}
if (!found) {
println("Invalid Entry (" + nameToRate + ")!" + LS
+ "Can not find the name supplied! Try again..." + LS);
nameToRate = "";
}
}
//.................................................
/* If we get to here then the name supplied
(regarless of letter case) is in the List. */
String rateNum = "";
while (rateNum.isEmpty()) {
println();
print("Enter your rating (1 to 5 or 'c' to cancel): --> ");
rateNum = USER_INPUT.nextLine().trim();
if (rateNum.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateNum.matches("[1-5]")) {
println("Invalid Entry (" + rateNum + ")! Try again..." + LS);
rateNum = "";
}
println();
}
// Set the rating.
int rating = Integer.valueOf(rateNum);
for (Properties p : prop.getProperties()) {
if (p.getPropertyName().equalsIgnoreCase(nameToRate)) {
int avgRating = p.getAverageRating();
p.addRating(rating);
println("Your rating of " + rating + " has been added to the accomodation" + LS
+ "named '" + nameToRate + "' which has moved its overall rating" + LS
+ "average from " + avgRating + " to an overall average rating of " +
p.getAverageRating() + "." + LS + "This is based on " +
p.getTotalNumberOfRatingsDone() + " rating(s) on the accomodation." + LS);
}
}
}
public static void println(Object... obj) {
if (obj.length > 0) {
System.out.println(obj[0]);
}
else {
System.out.println();
}
}
public static void printErr(Object... obj) {
if (obj.length > 0) {
System.err.println(obj[0]);
}
else {
System.err.println();
}
}
public static void print(Object... obj) {
if (obj.length > 0) {
System.out.print(obj[0]);
}
else {
System.out.print("");
}
}
}
The Properties class:
public class Properties {
public static java.util.List<Properties> properties = new java.util.ArrayList<>();
private String propertyName;
private String accomodationType;
private String description;
private String location;
private double pricePerDay;
private int averageRating = 0;
private int totalNumberOfRatings;
private boolean available;
// Constructor #1
public Properties() { }
// Constructor #2
public Properties(String propertyName, String accomodationType, String description,
String location, double pricePerDay, boolean available) {
this.propertyName = propertyName;
this.accomodationType = accomodationType;
this.description = description;
this.location = location;
this.pricePerDay = pricePerDay;
this.available = available;
}
// Getters & Setters
public java.util.List<Properties> getProperties() {
return properties;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getAccomodationType() {
return accomodationType;
}
public void setAccomodationType(String accomodationType) {
this.accomodationType = accomodationType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getPricePerDay() {
return pricePerDay;
}
public void setPricePerDay(double pricePerDay) {
this.pricePerDay = pricePerDay;
}
public int getAverageRating() {
return this.averageRating;
}
public void addRating(int rating) {
// Rateing is an integer value from 1 to 5.
// Where 1 is Bad and 5 Excellent.
if (rating < 1) { rating = 1; }
else if (rating > 5) { rating = 5; }
int sum = 0, r = 0;
for (Properties p : properties) {
if (p.propertyName.equalsIgnoreCase(this.propertyName)) {
r++;
sum += rating;
}
}
if (sum > 0 && r > 0) {
this.averageRating = sum / r;
}
else {
this.averageRating = rating;
}
this.totalNumberOfRatings++;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public String toString() {
return propertyName + ", " + accomodationType + ", " + description + ", "
+ location + ", " + pricePerDay + ", " + averageRating + ", "
+ available;
}
public String toStringTable(Properties p, boolean... addHeader) {
boolean applyHeader = false;
if (addHeader.length > 0) {
applyHeader = addHeader[0];
}
String symbol = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
String header = "", underline = "", ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
header = String.format("%-18s %-10s %-50s %-10s %-10s %-8s %-6s%n", "BNB Name",
"BNB Type", "BNB Description", "Location", "Price/Day", "Rating", "Avail.");
underline = String.join("", java.util.Collections.nCopies(header.length(), "=")) + ls;
if (applyHeader) {
sb.append(header).append(underline);
}
String[] desc = p.description.split("\\s+");
java.util.List<String> descTmp = new java.util.ArrayList<>();
StringBuilder sb2 = new StringBuilder("");
for (String str : desc) {
if ((sb2.toString() + " " + str).length() > 50) {
descTmp.add(sb2.toString());
sb2.setLength(0);
}
if (!sb2.toString().isEmpty()) {
sb2.append(" ");
}
sb2.append(str);
}
if (!sb2.toString().isEmpty()) {
descTmp.add(sb2.toString());
}
sb.append(String.format("%-18s %-10s %-50s %-12s " + symbol + "%-10.2f %-7s %-6s",
p.propertyName, p.accomodationType, descTmp.get(0), p.location,
p.pricePerDay, p.averageRating, (p.available ? "Yes" : "No")));
if (descTmp.size() > 1) {
for (int i = 1; i < descTmp.size(); i++) {
sb.append(ls).append(String.format("%-18s %-10s %-50s %-12s %-10s %-7s %-6s",
" "," ", descTmp.get(i), " ", " ", " ", " "));
}
}
return sb.toString();
}
public String[] getAllPropertyNames() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure names retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.propertyName)) {
tmp.add(prop.propertyName);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllAccomodationTypes() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure accomodations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.accomodationType)) {
tmp.add(prop.accomodationType);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public java.util.List<Properties> getPropertiesByLocation(String location) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.location.equalsIgnoreCase(location) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByAccomodationType(String accomodationType) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.accomodationType.equalsIgnoreCase(accomodationType) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByRating(int rating) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.averageRating == rating && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public int getTotalNumberOfRatingsDone() {
return this.totalNumberOfRatings;
}
public String[] getAllDescriptions() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure descriptions retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.description)) {
tmp.add(prop.description);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllLocations() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.location)) {
tmp.add(prop.location);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public double[] getAllPerDayPrices() {
java.util.List<Double> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.pricePerDay)) {
tmp.add(prop.pricePerDay);
}
}
// Convert List<Double> to double[]...
double[] prices = new double[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
prices[i] = tmp.get(i);
}
return prices;
}
}

How to search an array for a value?

I cant get case 3 and 4 to work correctly. I don't have an error but correct information is not displaying. For case 3, it displays the last item in the array even if another is entered.4 is not displaying.
These are the directions
The Video class should also have a static method called listVideosStarring that finds all movies that have
a particular star in them. This method takes a parameter that is the star’s name, and loop through the array
of products and concatenate the names of all the videos in the array that have the specified star in them.
Beware that not all the elements of this array point to Video instances; therefore, you will need to make
sure that a reference points to a Video instance before attempting to obtain the star. Also, since the Products
array is of type Product, you will need to treat the element as if it points to a Video to obtain the star's
name (this requires typecasting). Also keep in mind that because the member variable may contain more
than one star, you cannot assume that it necessarily equals the string entered by the user; instead you need
to see if the user’s entry is contained somewhere within the star member variable’s value.
Video and Automobile are subclasses of Product and products is the array
public class ProductsApplication {
public static void main (String [] args){
menuChoice();}
//method for menu choices
public static void menuChoice (){
boolean loopContinue = true;
while (loopContinue){
Scanner scan = new Scanner(System.in);
System.out.println("Choices are: ");
System.out.println("(1) Read products file");
System.out.println("(2) List products and show total inventory value");
System.out.println("(3) Display information about a product");
System.out.println("(4) List products with a given star");
System.out.println("(5) Show graph of inventory values");
System.out.println("(6) Quit");
System.out.println("What is your choice? (1-6)");
try {
String selection = scan.nextLine();
switch(selection)
{
case "1":
try{
//Create file
File inputFile = new File("C:/Users/Olivia/Desktop/CIS331/products.txt");
Scanner scanner = new Scanner(inputFile);
//read data from file
for (int i= 0; i< Product.MAXPRODUCTS; i++)
{
while(scanner.hasNext()){
String type = scanner.nextLine();
if (type.equals("PRODUCT")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
boolean add = Product.addProduct(pName, pDescription, pQuantity, pPrice);
}
if (type.equals("AUTOMOBILE")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
int y = Integer.parseInt(scanner.nextLine());
String mm = scanner.nextLine();
boolean add = Automobile.addAutomobile(pName, pDescription, pQuantity, pPrice, y, mm);
}
if(type.equals("VIDEO")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
String genere = scanner.nextLine();
String rate = scanner.nextLine();
int time = Integer.parseInt(scanner.nextLine());
String star = scanner.nextLine();
boolean add= Video.addVideo(pName, pDescription, pQuantity, pPrice, genere, rate, time, star);
}
}
}
System.out.println("File read successfully");
}
catch (FileNotFoundException e) {
System.out.println("Error reading" + e.toString());
}
break;
case "2":
System.out.println("List of products:");
System.out.println(Product.listProducts());
break;
case "3":
System.out.print("Enter the name of the product: ");
String findName = scan.nextLine();
int index = Product.findProduct(findName);
if (index >=0){
Product product = Product.getProduct(index);
System.out.println(product.prodInfo(true));}
else
{
System.out.println("Product was not found");
}
break;
case "4":
System.out.println("Enter the name of the star to search: ");
String starName = scan.nextLine();
System.out.println("Videos starring " + starName);
System.out.println(Video.listVideoStarring(starName));
break;
case "5":
break;
case "6":
System.exit(0);
break;
default:
System.out.println("error please try again");
break;
}
}
public class Product {
//instance member variables of the class
String productName;
private String productDescription;
private int productQuantity;
private double unitPrice;
//static member variables
protected static final int MAXPRODUCTS = 10;
protected static Product [] products;
protected static int totProducts =0;
//default constructor
public Product(){
this.productName = "PRODUCT";
this.productDescription = "DESCRIPTION";
this.productQuantity = 0;
this.unitPrice = 0.0 ;
}
//overloaded constructor
public Product(String name, String description, int quantity, double price){
setproductName(name);
setproductDescription(description);
setproductQuantity(quantity);
setunitPrice(price);
}
//getters and setters for instance varibles
public void setproductName(String name){
String firstLetter = name.substring(0,1).toUpperCase();
String nameCapitalized = firstLetter + name.substring(1). toLowerCase();
this.productName = nameCapitalized;
}
public String getproductName (){
return productName;
}
public void setproductDescription( String description){
this.productDescription = description;
}
public String getproductDescription(){
return productDescription;
}
public void setproductQuantity(int quantity){
if (quantity < 0){
this.productQuantity = 0;
}
else {
this.productQuantity = quantity;
}
}
public int getproductQuantity(){
return productQuantity;
}
public void setunitPrice (double price){
if (price<0){
this.unitPrice = 0.00;
}
else{
this.unitPrice = price;}
}
public double getunitPrice(){
return unitPrice;
}
//Methods
//Method for product information of a product instance
public String prodInfo(boolean booleanVariable){
if (booleanVariable){
NumberFormat numberFormat=NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getproductName() + System.lineSeparator()
+ "Product Description: " + getproductDescription() + System.lineSeparator()
+ "Product Quantity: " + getproductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getunitPrice()) + System.lineSeparator()
+ "Total value: " + numberFormat.format(totalValue());}
else {
return getproductName();
}
}
//Method that returns the total value of the product, quantity times price
public double totalValue(){
return (this.productQuantity * this.unitPrice);
}
/*Method that takes string parameters and tests to see if that parameters value
is equal to the value of products name, returns boolean*/
public boolean testsValue(String testString){
return this.getproductName().equalsIgnoreCase(productName);
}
//list names in the product array
public static String listProducts(){
StringBuilder s= new StringBuilder();
StringBuilder s2 = new StringBuilder();
if(products!= null && totProducts>0){
for(int i=0; i<totProducts; i++){
s.append(products[i].toString());
s.append(" ");
s.append(products[i].productName+"\n");
}
}
else{
s.append("No products available.");
}
return s.toString();
}
//find product in an array
public static int findProduct (String findName){
int index = -1;
if(products!=null && totProducts>0){
for( int i=0; i<totProducts; i++){
if(products[i].testsValue(findName))
{
index = i;
}
else {
index = -1;
return index;
}
}
}
return index;
}
//add product to array
public static boolean addProduct(String pName, String pDescription, int pQuantity, double pPrice){
if(totProducts== MAXPRODUCTS)
{
return false;
}
if(products == null){
products= new Product[MAXPRODUCTS];
}
Product newProduct = new Product(pName, pDescription, pQuantity, pPrice);
products[totProducts]= newProduct;
totProducts++;
return true;
}
// calculate total value of inventory in stock
public static double totInventoryValue(){
double sum = 0;
if (products != null && totProducts>0){
for(int i=0; i<totProducts; i++){
sum+= products[i].totalValue();
}
}
return sum;
}
//get accessor method for obtaining particular product from the index
public static Product getProduct(int index){
Product product= null;
if(products!= null && totProducts>0 && index>=0 && index<totProducts){
product = products[index];
}
return product;
}
// method added
public String toString(){
return "Product";
}
}
public class Video extends Product{
//instance member variables
private String movieType;
private String rating;
private int runningTime;
private String actors;
//default constructor
public Video(){
super();
this.movieType = "comedy";
this.rating ="Not Rated";
this.runningTime = 0;
this.actors ="Unknown";
}
//Overloaded constructor
public Video(String productName, String productDescription, int productQuantity, double unitPrice,
String movieType, String rating, int runningTime, String actors){
super(productName, productDescription, productQuantity, unitPrice);
setmovieType(movieType);
setrating(rating);
setrunningTime(runningTime);
setactors(actors);
}
//setters and getters
public void setmovieType(String movieType){
if(movieType.equals("comedy") || movieType.equals("drama") || movieType.equals("action")
|| movieType.equals("documentary")){
this.movieType = movieType;
}
else{
this.movieType = "comedy";
}
}
public String getmovieType(){
return movieType;
}
public void setrating(String rating){
if( rating.equals("G") || rating.equals("PG") || rating.equals("PG-13") || rating.equals("R")
|| rating.equals("Not Rated")){
this.rating = rating;
}
else{
this.rating = "Not Rated";
}
}
public String getrating(){
return rating;
}
public void setrunningTime(int runningTime){
if (runningTime < 30){
this.runningTime = 30;
}
if (runningTime > 500){
this.runningTime = 500;
}
else{
this.runningTime = runningTime;
}
}
public int getrunningTime(){
return runningTime;
}
public void setactors(String actors){
this.actors = actors;
}
public String getactors(){
return actors;
}
// to string that overrides product class
public String toString(){
return "Video";
}
// add video, creating instance
public static boolean addVideo(String productName, String productDescription, int productQuantity, double unitPrice,
String movieType, String rating, int runningTime, String star){
if(totProducts == MAXPRODUCTS)
{
return false;
}
if (products == null){
products= new Product[MAXPRODUCTS];
}
Video newVideo = new Video(productName, productDescription, productQuantity, unitPrice, movieType, rating,
runningTime, star);
Product.products[Product.totProducts]= newVideo;
Product.totProducts++;
return true;
}
//override prod info
public String prodInfo(boolean booleanVariable){
if (booleanVariable){
NumberFormat numberFormat=NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getproductName() + System.lineSeparator()
+ "Product Description: " + getproductDescription() + System.lineSeparator()
+ "Product Quantity: " + getproductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getunitPrice()) + System.lineSeparator()
+ "Total value: " + numberFormat.format(totalValue()) + System.lineSeparator() + "Movie Type: " + getmovieType() + System.lineSeparator()
+ "Running Time: " + getrunningTime() + System.lineSeparator() + "Rating: " + getrating() + System.lineSeparator()
+ "Stars: " + getactors() ;}
else {
return getproductName();
}
}
//new method to find movies that a star is in a movie
public static String listVideoStarring(String starName){
StringBuilder sb = new StringBuilder();
for (int i= 0; i<totProducts; i++){
if (((Video)products[i]).contains(starName)){
sb.append(((Video)products[i]).productName.toString());
}
}
return sb.toString();
}
}
`
This is the text file I read in
PRODUCT
Generic product
This is the description for product 1.
15000
12.50
VIDEO
Shrek
Animated movie about an ogre, a princess, and a donkey.
25000
15.25
comedy
PG
120
Mike Myers, Eddie Murphy, Cameron Diaz
AUTOMOBILE
Fancy car
A very cool and fast red sports car.
12
33999.99
2020
Ford Mustang
VIDEO
Goldmember
Hijinks of a British spy.
13000
8.45
comedy
PG-13
90
Mike Myers, Mindy Sterling, Michael Caine, Seth Greene, Heather Graham
AUTOMOBILE
Eco-friendly car
Better for the environment.
18
27999.99
2020
Toyota Prius
VIDEO
Black Panther
A Marvel Comics superhero movie
14000
13.75
drama
PG-13
90
Chadwick Boseman, Lupita Nyong'o, Michael B. Jordan
Ideally, class Product should be abstract. You can't really create a "product" but you can create a video and you can create an automobile. However, from your code it appears that you can create a "generic" Product so in your circumstances, class Product should not be made abstract.
Default constructors don't make sense because a productName should be used to identify a Product object and therefore each Product object should have a unique productName. I would remove the default constructors.
Your identifiers do not strictly adhere to Java naming conventions. In the below code I have made the relevant changes.
In method findProduct(), of class Product, remove the else. You are only testing the first element in the array products. I assume that each Product must have a unique productName and therefore the method should be:
public static int findProduct(String findName) {
int index = -1;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
if (products[i].testsValue(findName)) {
index = i;
break;
}
}
}
return index;
}
You should add another addProduct() [static] method to class Product with a single Product argument. Then you can add Video objects and Automobile objects to products array.
public static boolean addProduct(Product newProduct) {
if (products == null) {
products = new Product[MAXPRODUCTS];
totProducts = 0;
}
boolean added = false;
if (newProduct != null && totProducts < MAXPRODUCTS) {
products[totProducts] = newProduct;
totProducts++;
added = true;
}
return added;
}
Consequently, you can change your existing addProduct() method.
public static boolean addProduct(String pName,
String pDescription,
int pQuantity,
double pPrice) {
return addProduct(new Product(pName, pDescription, pQuantity, pPrice));
}
When reading the products.txt file, you should use try-with-resources to make sure that the file gets closed. Also, the for loop is not required. You should change the while loop so that it stops reading the file after totProducts equals MAXPRODUCTS.
You should almost always print the stack trace of exceptions rather than just print the error message as this will help you to locate the code that is causing the error.
Method testsValue(), in class Product is also wrong. You should check the parameter value.
public boolean testsValue(String testString) {
return this.getProductName().equalsIgnoreCase(testString);
}
Finally, you need to change method listVideoStarring(), in class Video.
public static String listVideoStarring(String starName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totProducts; i++) {
if (products[i] instanceof Video) {
Video video = (Video) products[i];
if (video.getActors().contains(starName)) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(video.getProductName());
}
}
}
return sb.toString();
}
Here is complete code.
Class Video
import java.text.NumberFormat;
import java.util.Locale;
public class Video extends Product {
// instance member variables
private String movieType;
private String rating;
private int runningTime;
private String actors;
// Overloaded constructor
public Video(String productName,
String productDescription,
int productQuantity,
double unitPrice,
String movieType,
String rating,
int runningTime,
String actors) {
super(productName, productDescription, productQuantity, unitPrice);
setMovieType(movieType);
setRating(rating);
setRunningTime(runningTime);
setActors(actors);
}
// setters and getters
public void setMovieType(String movieType) {
if (movieType.equals("comedy") || movieType.equals("drama") || movieType.equals("action")
|| movieType.equals("documentary")) {
this.movieType = movieType;
}
else {
this.movieType = "comedy";
}
}
public String getMovieType() {
return movieType;
}
public void setRating(String rating) {
if (rating.equals("G") || rating.equals("PG") || rating.equals("PG-13")
|| rating.equals("R") || rating.equals("Not Rated")) {
this.rating = rating;
}
else {
this.rating = "Not Rated";
}
}
public String getRating() {
return rating;
}
public void setRunningTime(int runningTime) {
if (runningTime < 30) {
this.runningTime = 30;
}
if (runningTime > 500) {
this.runningTime = 500;
}
else {
this.runningTime = runningTime;
}
}
public int getRunningTime() {
return runningTime;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getActors() {
return actors;
}
// to string that overrides product class
public String toString() {
return "Video";
}
// add video, creating instance
public static boolean addVideo(String productName, String productDescription,
int productQuantity, double unitPrice, String movieType, String rating, int runningTime,
String star) {
if (totProducts == MAXPRODUCTS) {
return false;
}
if (products == null) {
products = new Product[MAXPRODUCTS];
}
Video newVideo = new Video(productName, productDescription, productQuantity, unitPrice,
movieType, rating, runningTime, star);
Product.products[Product.totProducts] = newVideo;
Product.totProducts++;
return true;
}
// override prod info
public String prodInfo(boolean booleanVariable) {
if (booleanVariable) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getProductName() + System.lineSeparator()
+ "Product Description: " + getProductDescription() + System.lineSeparator()
+ "Product Quantity: " + getProductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getUnitPrice())
+ System.lineSeparator() + "Total value: " + numberFormat.format(totalValue())
+ System.lineSeparator() + "Movie Type: " + getMovieType()
+ System.lineSeparator() + "Running Time: " + getRunningTime()
+ System.lineSeparator() + "Rating: " + getRating() + System.lineSeparator()
+ "Stars: " + getActors();
}
else {
return getProductName();
}
}
// new method to find movies that a star is in a movie
public static String listVideoStarring(String starName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totProducts; i++) {
if (products[i] instanceof Video) {
Video video = (Video) products[i];
if (video.getActors().contains(starName)) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(video.getProductName());
}
}
}
return sb.toString();
}
}
Class Product
import java.text.NumberFormat;
import java.util.Locale;
public class Product {
// instance member variables of the class
String productName;
private String productDescription;
private int productQuantity;
private double unitPrice;
// static member variables
protected static final int MAXPRODUCTS = 10;
protected static Product[] products;
protected static int totProducts = 0;
// overloaded constructor
public Product(String name, String description, int quantity, double price) {
setProductName(name);
setProductDescription(description);
setProductQuantity(quantity);
setUnitPrice(price);
}
// getters and setters for instance varibles
public void setProductName(String name) {
String firstLetter = name.substring(0, 1).toUpperCase();
String nameCapitalized = firstLetter + name.substring(1).toLowerCase();
this.productName = nameCapitalized;
}
public String getProductName() {
return productName;
}
public void setProductDescription(String description) {
this.productDescription = description;
}
public String getProductDescription() {
return productDescription;
}
public void setProductQuantity(int quantity) {
if (quantity < 0) {
this.productQuantity = 0;
}
else {
this.productQuantity = quantity;
}
}
public int getProductQuantity() {
return productQuantity;
}
public void setUnitPrice(double price) {
if (price < 0) {
this.unitPrice = 0.00;
}
else {
this.unitPrice = price;
}
}
public double getUnitPrice() {
return unitPrice;
}
// Methods
// Method for product information of a product instance
public String prodInfo(boolean booleanVariable) {
if (booleanVariable) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getProductName() + System.lineSeparator()
+ "Product Description: " + getProductDescription() + System.lineSeparator()
+ "Product Quantity: " + getProductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getUnitPrice())
+ System.lineSeparator() + "Total value: " + numberFormat.format(totalValue());
}
else {
return getProductName();
}
}
// Method that returns the total value of the product, quantity times price
public double totalValue() {
return (this.productQuantity * this.unitPrice);
}
/*
* Method that takes string parameters and tests to see if that parameters value
* is equal to the value of products name, returns boolean
*/
public boolean testsValue(String testString) {
return this.getProductName().equalsIgnoreCase(testString);
}
// list names in the product array
public static String listProducts() {
StringBuilder s = new StringBuilder();
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
s.append(products[i].toString());
s.append(" ");
s.append(products[i].productName + "\n");
}
}
else {
s.append("No products available.");
}
return s.toString();
}
// find product in an array
public static int findProduct(String findName) {
int index = -1;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
if (products[i].testsValue(findName)) {
index = i;
break;
}
}
}
return index;
}
// add product to array
public static boolean addProduct(String pName,
String pDescription,
int pQuantity,
double pPrice) {
return addProduct(new Product(pName, pDescription, pQuantity, pPrice));
}
public static boolean addProduct(Product newProduct) {
if (products == null) {
products = new Product[MAXPRODUCTS];
totProducts = 0;
}
boolean added = false;
if (newProduct != null && totProducts < MAXPRODUCTS) {
products[totProducts] = newProduct;
totProducts++;
added = true;
}
return added;
}
// calculate total value of inventory in stock
public static double totInventoryValue() {
double sum = 0;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
sum += products[i].totalValue();
}
}
return sum;
}
// get accessor method for obtaining particular product from the index
public static Product getProduct(int index) {
Product product = null;
if (products != null && totProducts > 0 && index >= 0 && index < totProducts) {
product = products[index];
}
return product;
}
// method added
public String toString() {
return "Product";
}
}
Class ProductsApplication
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ProductsApplication {
public static void main(String[] args) {
menuChoice();
}
// method for menu choices
public static void menuChoice() {
boolean loopContinue = true;
while (loopContinue) {
Scanner scan = new Scanner(System.in);
System.out.println("Choices are: ");
System.out.println("(1) Read products file");
System.out.println("(2) List products and show total inventory value");
System.out.println("(3) Display information about a product");
System.out.println("(4) List products with a given star");
System.out.println("(5) Show graph of inventory values");
System.out.println("(6) Quit");
System.out.println("What is your choice? (1-6)");
try {
String selection = scan.nextLine();
switch (selection) {
case "1":
// Create file
File inputFile = new File("C:/Users/Olivia/Desktop/CIS331products.txt");
try (Scanner scanner = new Scanner(inputFile)) {
// read data from file
while (scanner.hasNextLine()
&& Product.totProducts < Product.MAXPRODUCTS) {
String type = scanner.nextLine();
if (type.equals("PRODUCT")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
boolean add = Product.addProduct(pName,
pDescription,
pQuantity,
pPrice);
}
if (type.equals("AUTOMOBILE")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
int y = Integer.parseInt(scanner.nextLine());
String mm = scanner.nextLine();
boolean add = Product.addProduct(new Automobile(pName,
pDescription,
pQuantity,
pPrice,
y,
mm));
}
if (type.equals("VIDEO")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
String genere = scanner.nextLine();
String rate = scanner.nextLine();
int time = Integer.parseInt(scanner.nextLine());
String star = scanner.nextLine();
boolean add = Product.addProduct(new Video(pName,
pDescription,
pQuantity,
pPrice,
genere,
rate,
time,
star));
}
}
System.out.println("File read successfully");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case "2":
System.out.println("List of products:");
System.out.println(Product.listProducts());
break;
case "3":
System.out.print("Enter the name of the product: ");
String findName = scan.nextLine();
int index = Product.findProduct(findName);
if (index >= 0) {
Product product = Product.getProduct(index);
System.out.println(product.prodInfo(true));
}
else {
System.out.println("Product was not found");
}
break;
case "4":
System.out.println("Enter the name of the star to search: ");
String starName = scan.nextLine();
System.out.println("Videos starring " + starName);
System.out.println(Video.listVideoStarring(starName));
break;
case "5":
break;
case "6":
System.exit(0);
break;
default:
System.out.println("error please try again");
break;
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
}

how to select players join the game and start a game

I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static 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;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static 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 static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.

Why does this continue to ask for strings?

I am working on a program that is supposed to help students study the presidents. I am using a stack. It is supposed to ask for user input and then it compares the input to the top of the stack. If it is correct it removes the top item. otherwise it asks for the next president. When I get to the end it asks again for the next president even though the stack should be empty.
Here is my main program.
package namepresidents;
import java.util.Scanner;
public class NamePresidents
{
//=========================MAIN=============================================
public static void main(String[] args)
{
UnboundedStackInterface<String> presidents;
presidents = new LinkedStack<String>();
presidents.push("George Washington");
presidents.push("John Adams");
presidents.push("Thomas Jefferson");
presidents.push("James Madison");
presidents.push("James Monroe");
presidents.push("John Quincy Adams");
presidents.push("Andrew Jackson");
presidents.push("Martin Van Buren");
presidents.push("James Madison");
presidents.push("William Henry Harrison");
presidents.push("John Tyler");
presidents.push("James K Polk");
presidents.push("Zachary Taylor");
presidents.push("James Madison");
presidents.push("Millard Fillmore");
presidents.push("Franklin Pierce");
presidents.push("James Buchanan");
presidents.push("Abraham Lincoln");
presidents.push("Andrew Johnson");
presidents.push("Ulysses S Grant");
presidents.push("Rutherford B. Hayes");
presidents.push("James A Garfield");
presidents.push("Chester A Arthur ");
presidents.push("Grover Cleveland");
presidents.push("Benjamin Harrison");
presidents.push("Grover Cleveland");
presidents.push("William McKinley");
presidents.push("William H Taft");
presidents.push("Woodrow Wilson");
presidents.push("Warren G Harding");
presidents.push("Calvin Coolidge");
presidents.push("Herbert Hoover");
presidents.push("Franklin D Roosevelt");
presidents.push("Harry S Truman");
presidents.push("Dwight D Eisenhower");
presidents.push("John F Kennedy");
presidents.push("Lyndon B Johnson");
presidents.push("Richard M Nixon");
presidents.push("Gerald R Ford");
presidents.push("Jimmy Carter");
presidents.push("Ronald Reagan");
presidents.push("George Bush");
presidents.push("Bill Clinton");
presidents.push("George W Bush");
presidents.push("Barack Obama");
UnboundedStackInterface<String> wrongAnswer;
wrongAnswer = new LinkedStack<String>();
String menu = "Would you like to study: \n"
+ "1. All the presidents \n"
+ "2. The first half \n"
+ "3. The second half \n"
+ "4. In reverse \n"
+ "0. Exit \n";
System.out.print(menu);
Scanner in = new Scanner(System.in);
int option = in.nextInt();
String studentPresidents = in.nextLine();
switch(option)
{
case 1:
do
{
System.out.print("Enter the next president: ");
studentPresidents = in.nextLine();
if(studentPresidents.equalsIgnoreCase(presidents.top()))
{
presidents.pop();
}
else
{
wrongAnswer.push(studentPresidents);
System.out.println("That is not correct. Try Again!");
}
}while(!presidents.isEmpty());
do
{
System.out.print("You missed: \n" + wrongAnswer.top());
wrongAnswer.pop();
}while(!wrongAnswer.isEmpty());
break;
case 2: UnboundedStackInterface<String> firstHalf;
firstHalf = new LinkedStack<String>();
firstHalf.push("George Washington");
firstHalf.push("John Adams");
firstHalf.push("Thomas Jefferson");
firstHalf.push("James Madison");
firstHalf.push("James Monroe");
firstHalf.push("John Quincy Adams");
firstHalf.push("Andrew Jackson");
firstHalf.push("Martin Van Buren");
firstHalf.push("James Madison");
firstHalf.push("William Henry Harrison");
firstHalf.push("John Tyler");
firstHalf.push("James K Polk");
firstHalf.push("Zachary Taylor");
firstHalf.push("James Madison");
firstHalf.push("Millard Fillmore");
firstHalf.push("Franklin Pierce");
firstHalf.push("James Buchanan");
firstHalf.push("Abraham Lincoln");
firstHalf.push("Andrew Johnson");
firstHalf.push("Ulysses S Grant");
firstHalf.push("Rutherford B Hayes");
firstHalf.push("James A Garfield");
do
{
System.out.print("Enter the next president: ");
studentPresidents = in.nextLine();
if(studentPresidents.equalsIgnoreCase(firstHalf.top()))
{
firstHalf.pop();
}
else
{
wrongAnswer.push(studentPresidents);
System.out.println("That is not correct. Try Again!");
}
}while(!presidents.isEmpty());
do
{
System.out.print("You missed: \n" + wrongAnswer.top());
wrongAnswer.pop();
}while(!wrongAnswer.isEmpty());
break;
case 3: UnboundedStackInterface<String> lastHalf;
lastHalf = new LinkedStack<String>();
lastHalf.push("Chester A Arthur");
lastHalf.push("Grover Cleveland");
lastHalf.push("Benjamin Harrison");
lastHalf.push("Grover Cleveland");
lastHalf.push("William McKinley");
lastHalf.push("William H Taft");
lastHalf.push("Woodrow Wilson");
lastHalf.push("Warren G Harding");
lastHalf.push("Calvin Coolidge");
lastHalf.push("Herbert Hoover");
lastHalf.push("Franklin D Roosevelt");
lastHalf.push("Harry S Truman");
lastHalf.push("Dwight D Eisenhower");
lastHalf.push("John F Kennedy");
lastHalf.push("Lyndon B Johnson");
lastHalf.push("Richard M Nixon");
lastHalf.push("Gerald R Ford");
lastHalf.push("Jimmy Carter");
lastHalf.push("Ronald Reagan");
lastHalf.push("George Bush");
lastHalf.push("Bill Clinton");
lastHalf.push("George W Bush");
lastHalf.push("Barack Obama");
do
{
System.out.print("Enter the next president: ");
studentPresidents = in.nextLine();
if(studentPresidents.equalsIgnoreCase(lastHalf.top()))
{
lastHalf.pop();
}
else
{
wrongAnswer.push(studentPresidents);
System.out.println("That is not correct. Try Again!");
}
} while(!presidents.isEmpty());
do
{
System.out.print("You missed: \n" + wrongAnswer.top());
wrongAnswer.pop();
}while(!wrongAnswer.isEmpty());
break;
case 4: UnboundedStackInterface<String> reversePres;
reversePres = new LinkedStack<String>();
do
{
reversePres.push(presidents.top());
presidents.pop();
}while(!presidents.isEmpty());
do
{
System.out.print("Enter the next president: ");
studentPresidents = in.nextLine();
if(studentPresidents.equalsIgnoreCase(reversePres.top()))
{
reversePres.pop();
}
else
{
wrongAnswer.push(studentPresidents);
System.out.println("That is not correct. Try Again!");
}
}while(!reversePres.isEmpty());
do
{
System.out.print("You missed: \n" + wrongAnswer.top());
wrongAnswer.pop();
}while(!wrongAnswer.isEmpty());
break;
case 0: System.out.println("Exit!");
break;
default: break;
}
}
}
Here is my LinkedStack class
package namepresidents;
public class LinkedStack<T> implements
UnboundedStackInterface<T>
{
protected LLNode<T> top;
//=================================constructor==============================
public LinkedStack()
{
top = null;
}
//===================================push===================================
public void push(T element)
{
LLNode<T> newNode = new LLNode<>(element);
newNode.setLink(top);
top = newNode;
}
//====================================pop===================================
public void pop()
{
if (!isEmpty())
{
top = top.getLink();
}
else
{
throw new StackUnderflowException("Pop"
+ "Attempted on empty stack.");
}
}
//=====================================top==================================
public T top()
{
if (!isEmpty())
{
return top.getInfo();
}
else
{
throw new StackUnderflowException("top"
+ "Attempted on empty stack.");
}
}
//======================================isEmpty=============================
public boolean isEmpty()
{
if (top == null)
{
return true;
}
else
{
return false;
}
}
}
Here is my LLNODE class
package namepresidents;
public class LLNode<T>
{
private T info;
private LLNode<T> link;
public LLNode(T info)
{
this.info = info;
link = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLink(LLNode<T> link)
{
this.link = link;
}
public LLNode<T> getLink()
{
return link;
}
}
You have a mistake in options 2 and 3. Look at this reduced loop code:
do
{
if(studentPresidents.equalsIgnoreCase(firstHalf.top()))
{
firstHalf.pop(); // pops firstHalf
}
}while(!presidents.isEmpty()); // tests presidents
This is why copy and paste programming is bad. It is prone to errors.
For cases 2 and 3 your while() test should be checking the half lists, rather than presidents list.

Categories