I've got a linked list class with a controller class and a test class which is the main class. The code runs and accepts user input, however when I click to display all team members entered it is empty.
Where have I gone wrong? How do I get all the team members to entered to be displayed?
public class TeamMember {
private LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
this.teamMembers = new LinkedList<>();
}
}
package com.view;
import com.controller.TeamMemberController;
import com.model.TeamMember;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TeamMemberController teamMemberController = new TeamMemberController();
int userInput;
do {
System.out.println("1. Add a new team member");
System.out.println("2. Find and display a team member");
System.out.println("3. Remove a team member");
System.out.println("4. Display all team members");
System.out.println("0. Quit");
//Validate user input
try {
userInput = scan.nextInt();
scan.nextLine();
} catch (InputMismatchException e) {
//if anything other than an integer is entered.
//The "scan.nextLine" fix above will not be triggered.
//It has to appear in the catch as well.
scan.nextLine();
userInput = 5;
}
switch (userInput) {
case 0:
userInput = teamMemberController.quit();
break;
case 1:
System.out.println("**********\n" + teamMemberController.addTeamMember());
break;
case 2:
System.out.println("**********\n" + teamMemberController.findTeamMember());
break;
case 3:
System.out.println("**********\n" + teamMemberController.removeTeamMember());
break;
case 4:
teamMemberController.displayAllTeamMembers();
break;
default:
System.out.println("*** Please Make another selection ***");
System.out.println("");
break;
}
} while (userInput != 0);
}
}
package com.controller;
import com.model.TeamMember;
import java.util.LinkedList;
import java.util.Scanner;
public class TeamMemberController {
private TeamMember teamMember;
public TeamMemberController() {
String name = null;
this.teamMember = new TeamMember(name);
}
Scanner scan = new Scanner(System.in);
public String addTeamMember() {
System.out.println("To go back press 0");
String name = null;
boolean keepLooping = true;
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//user enters name
while (keepLooping) {
System.out.println("Enter team member name");
//project names MUST be UNIQUE
name = scan.nextLine();
if (name.equals("0")) {
return "team member not added";
}
if (!this.checkIfTeamMemberNameExists(name)) {
keepLooping = false;
} else {
System.out.println("Team Member already exists");
System.out.println("");
}
}
//add team member to collection
teamMembers.add(new TeamMember(name));
teamMember.setTeamMembers(teamMembers);
//returns true when a team member has been successfully added
return "Name: " + name + "\n--Added--";
}
public String findTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if the company has no team members no need to continue
if (teamMembers.isEmpty()) {
return "Sorry no team members";
}
//get here company must have team members
System.out.println("Enter team member name");
String name = scan.nextLine();
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return "Name: " + t.getTeamMembers();
}
}
return "Team member not found";
}
public String removeTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
System.out.println("Enter name of team member to remove");
System.out.println("Enter 0 to exit");
String projectToRemove = scan.nextLine();
boolean removed = false;
if (projectToRemove.equals("0")) {
return "No project removed";
}
//check existing team member names against the user input one
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(removeTeamMember())) {
teamMembers.remove(t);
removed = true;
}
}
if (removed) {
teamMember.setTeamMembers(teamMembers);
} else
return "No team member found";
return removeTeamMember() + " has successfully been removed";
}
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getTeamMembers() + " ");
}
}
public int quit() {
System.out.println("Are you sure you want to quit? y/n");
String userResponse = scan.nextLine();
boolean loop = true;
while (loop) {
if (userResponse.equalsIgnoreCase("y")) {
System.out.println("Program ending");
return 0;
} else if (userResponse.equalsIgnoreCase("n"))
return 5;
}
return 0;
}
public boolean checkIfTeamMemberNameExists(String name) {
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if a team member with the same name already exists return true
if (!teamMembers.isEmpty()) {
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return true;
}
}
}
return false;
}
}
This is the output I'm getting. How do I get it to print the names entered?
[1]: https://i.stack.imgur.com/FVhVm.png
The first problem is that TeamMembers don't remember the names you give them. Add a field for the name, and a method to retrieve it:
private String name;
public TeamMember(String name) {
this.name = name;
this.teamMembers = new LinkedList<>();
}
public String getName() {
return name;
}
The second problem is that displayAllTeamMembers does not display the "name" of the team member. There was no way it could have done it because the team members didn't even have a name, but now they do.
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getName());
}
}
A third possible problem is that each individual "team member" has a list of team members. That just seems confusing to me and makes me wonder if you have misread the instructions for this exercise.
Below is the minimum code change required to make your code work. But I would suggest to follow design patterns before if you a build a working prod ready system around this code.
public class TeamMember {
private static LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
if(teamMembers==null) {
teamMembers = new LinkedList<>();
}
}
}
Related
I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
public class Salesperson
{
private String salesName;
private int salesID;
private double annualSales;
public Salesperson(String salesName, int salesIDNum, double yearlySales)
{
this.salesName = salesName;
salesID = salesIDNum;
annualSales = yearlySales;
}
public String getSalesName()
{
return salesName;
}
public void setSalesName(String salesName)
{
this.salesName = salesName;
}
public double getSalesID()
{
return salesID;
}
public void setSalesID(int salesIDNum)
{
salesID = salesIDNum;
}
public double getAnnualSales()
{
return annualSales;
}
public void setAnnualSales(double yearlySales)
{
annualSales = yearlySales;
}
#Override
public String toString()
{
return String.format("%s-%-10s%-10.2f", salesName,
salesID, annualSales);
}
}
And my code for application looks like this:
import java.util.Arrays;
import java.util.Scanner;
public class CreateSalesperson
{
private static final Scanner USER_INPUT = new Scanner(System.in);
private static final int UPPER_SIZE_LIMIT = 20;
private static final int LOWER_SIZE_LIMIT = 0;
private static Salesperson[] salesStaffInDatabase = new
Salesperson[20];
private static int numOfSalesPpl = 0;
private static boolean loop = true;
public static void main(String[] args)
{
String selection;
selection = programMenu();
String response;
while(loop)
switch(selection)
{
case "A":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "a":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "C":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "c":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "E":
System.out.print("You Are Leaving Database");
loop = false;
break;
case "e":
System.out.print("You Are Leaving Database");
loop = false;
break;
}
}
public static void changeRecord()
{
String idNum;
String salesName;
double salesAmount;
String response;
System.out.print("Enter Sales ID: ");
idNum = USER_INPUT.nextLine();
if(isValidID(idNum))
{
int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
System.out.println(salesStaffInDatabase[searchResult]);
}
else
{
System.out.println("Invalid Sales ID");
}
}
public static boolean isValidID(String idNum)
{
boolean isValid= false;
for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
{
if(salesStaffInDatabase[val].equals(idNum))
{
isValid = true;
}
}
return isValid;
}
public static void addRecord()
{
int idNum;
String salesName;
double salesAmount;
String idNo;
String response;
do
{
System.out.print("Please enter sales ID: ");
idNum = USER_INPUT.nextInt();
idNo = Integer.toString(idNum);
if(idNo.length() != 8)
System.out.println("Sales ID must be 8 digits long: ");
}
while(idNo.length() < 8 || idNo.length() > 8);
System.out.print("Name: ");
salesName = USER_INPUT.nextLine();
USER_INPUT.nextLine();
System.out.print("Sales Amount: ");
salesAmount = Double.parseDouble(USER_INPUT.nextLine());
salesStaffInDatabase[numOfSalesPpl] = new
Salesperson(salesName,idNum,salesAmount);
salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);
System.out.print("Do you want to display database Y/N?: ");
response = USER_INPUT.nextLine();
while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
{
displayDatabase();
}
}
public static void displayDatabase()
{
for(int val=0;val < numOfSalesPpl; val++)
{
System.out.println(salesStaffInDatabase[val]);
}
}
public static String programMenu()
{
String selection;
do
{
System.out.println("(A)dd a Record");
System.out.println("(C)hange a Record");
System.out.println("(E)xit Database");
System.out.print("Enter selection: ");
selection = USER_INPUT.nextLine();
}
while(!selection.equalsIgnoreCase("a") &&
!selection.equalsIgnoreCase("c")
&& !selection.equalsIgnoreCase("e"));
return selection;
}
}
=================================================================
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
#Override public String toString() {
return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
edit the toString()method in Salesperson class :
#Override
public String toString() {
return "Salesperson{" +
"salesFirstName='" + salesFirstName + '\'' +
", salesLastName='" + salesLastName + '\'' +
", salesID='" + salesID + '\'' +
", annualSales=" + String.format("%-10.2f", annualSales)+
'}';
}
Hello I think I'm really having a hard time with this part. I'm making a program that accepts a value from the user a first name and last name, and then Queues it (CASE1). Then is able to dequeue it (CASE2) and finally show everything on the list. There are no errors on the IDE, but I cant get the result that I want, At CASE 2 it throws the exception error, means that the list that gets passed to it is empty. At CASE 3 no values are shown. How do I fix this?
import java.util.*;
import java.util.Iterator;
class Customer2 {
public String lastName;
public String firstName;
public Customer2() {
}
public Customer2(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer2 extends Customer2 {
public double hourlyRate;
public HourlyCustomer2(String last, String first) {
super(last, first);
}
}
class Queue1<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
// return a Customer2 with null values if empty? (up to you)
return list.remove(0);
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public E removeFirst() {
return list.removeFirst();
}
public E getFirst() {
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
Queue1<Customer2> empList;
empList = new Queue1<Customer2>();
Queue1<HourlyCustomer2> hList;
hList = new Queue1<HourlyCustomer2>();
do {
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,View queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try {
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer2(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
break;
case 3:
System.out.println("\nThe Customer's names are: \n");
Iterator<Customer2> it = empList.iterator();
while (it.hasNext()) {
System.out.println("\nThe customers' names are: \n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
} while(choice != 0);
}
}
Look at your custom queue; you forgot to put the logic in your hasNext method. It will always return false. Therefore your addItems loop will never add any items to the queue.
If you need a hint towards how to do the hasNext(), my recommendation is to look at the size of your list and make a simple comparison.
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
PS: I noticed that your code also shows the next in line. You might want to check if it's empty or hasNext() before that to not get a crash if the list was empty after that dequeuing.
I can't get my program to read from a file and populate my array.
This is my StudentAccount class which contains my array.
The array needs to be able to populate from a text file
and also add a Student by using the Scanner class.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Student {
// attributes
private StudentAccount[] list; // to hold the accounts
private int numStudents;
// to keep track of the number of accounts in the list
// methods
// the constructor
public Student() {
// size array with parameter
list = new StudentAccount[20];
numStudents = 0;
}
// helper method to find the index of a specified account
private int search(String studentNameIn) {
for (int i = 0; i < numStudents; i++) {
StudentAccount tempAccount = list[i];
// find the account at index i
String tempName = tempAccount.getStudentName();
// get account number
if (tempName.equals(studentNameIn))
// if this is the account we are looking for
{
return i; // return the index
}
}
return -999;
}
// return the total number of accounts in the list
public int getTotal() {
return numStudents;
}
// check if the list is empty
public boolean isEmpty() {
if (numStudents == 0) {
return true; // list is empty
} else {
return false; // list is not empty
}
}
// check if the list is full
public boolean isFull() {
if (numStudents == list.length) {
return true; // list is full
} else {
return false; // list is empty
}
}
// add an item to the array
public boolean add(StudentAccount accountIn) {
if (!isFull()) // check if list is full
{
list[numStudents] = accountIn; // add item
numStudents++; // increment total
return true; // indicate success
} else {
return false; // indicate failure
}
}
// return an account at a particular place in the list
public StudentAccount getItem(int positionIn) {
if (positionIn < 1 || positionIn > numStudents) {
return null; // indicate invalid index
} else {
return list[positionIn - 1];
}
}
// return an account with a particular account number
public StudentAccount getItem(String studentNameIn) {
int index;
index = search(studentNameIn);
if (index == -999) {
return null; // indicate invalid index
} else {
return list[index];
}
}
// remove an account
public boolean remove(String numberIn) {
int index = search(numberIn); // find index of account
if (index == -999) // if no such account
{
return false; // remove was unsuccessful
} else { // overwrite items by shifting other items along
for (int i = index; i <= numStudents - 2; i++) {
list[i] = list[i + 1];
}
numStudents--; // decrement total number of accounts
return true; // remove was successful
}
}
static void writeToFile() {
}
static void readFromFile() {
try {
FileInputStream fstream = new FileInputStream("Students.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
in.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
}
}
This is my Student class:
public class StudentAccount {
private String studentName;
private String studentDOB;
private String studentAddress;
private String studentGender;
public final static String MALE = "m";
public final static String FEMALE = "f";
public StudentAccount(String nameIn, String dobIn,
String addressIn, String genderIn) {
this.studentName = nameIn;
this.studentDOB = dobIn;
this.studentAddress = addressIn;
this.studentGender = genderIn;
}
public String getStudentName() {
return studentName;
}
public String getStudentDOB() {
return studentDOB;
}
public String getStudentAddress() {
return studentAddress;
}
public String getStudentGender() {
return studentGender;
}
public static boolean validateGender(String genderIn) {
return (genderIn.toLowerCase().compareTo(MALE) == 0)
|| (genderIn.toLowerCase().compareTo(FEMALE) == 0);
}
}
Finally this is my main class which runs my program.
The method for readFromFile
I need it to read the file one line at a time and save each line as one student record in the array. It reads in from file but doesn't put any data in the array.
public class EnrolmentRegister {
private static String lecturer = "John Smyth";
public static void main(String[] args) {
char choice;
Student newStudent = new Student();
Student.readFromFile();
do {
System.out.println();
System.out.println("1. Add A New Student Account");
System.out.println("2. Remove A Student Account");
System.out.println("3. Get Course Details ");
System.out.println("4. Quit");
System.out.println();
System.out.println("Please Choose One Of The Options Above");
choice = InputScanner.nextChar();
System.out.println();
switch (choice) {
case '1':
option1(newStudent);
break;
case '2':
option2(newStudent);
break;
case '3':
option3(newStudent);
break;
case '4':
break;
default:
System.out.println("Invalid entry");
}
} while (choice != '4');
}
static void option1(Student StudentIn) {
String gender;
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
System.out.print("Enter Student Date Of Birth: ");
String studentDOB = InputScanner.nextString();
System.out.print("Enter Student Address: ");
String studentAddress = InputScanner.nextString();
do {
System.out.print("Enter Student Gender m/f: ");
gender = InputScanner.nextString();
} while (!StudentAccount.validateGender(gender));
// create new account
StudentAccount account =
new StudentAccount(studentName, studentDOB,
studentAddress, gender);
// add account to list
boolean ok = StudentIn.add(account);
if (!ok) {
System.out.println("The list is full");
} else {
System.out.println("Account created");
}
}
static void option2(Student StudentIn) {
// get account number of account to remove
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
// delete item if it exists
boolean ok = StudentIn.remove(studentName);
if (!ok) {
System.out.println("No such Student Name");
} else {
System.out.println("Account removed");
}
}
static void option3(Student StudentIn) {
System.out.println("COM 180, " + lecturer);
}
static void option4(Student StudentIn) {
}
static void option5(Student StudentIn) {
}
}
/*When I call the readFromFile method and print it I get each
line of text from the text file but don't know how
to put each line from the file into the array. This is
homework and been at this for days. I know its probably
something simple but I cant work it out. Any help would
be greatly appreciated. Thanks*/
I do not see you declare InputScanner anywhere as scanner:
Scanner InputScanner = new Scanner(new File("fileNameGoesHere"));
Yet you call it multiple times in main:
choice = InputScanner.nextChar();
String studentName = InputScanner.nextString();
Note: do not capitalize variable names since it may be confused with Object types.
I have been stuck on the same problem for days and have googled everything I can think of and I give up. I am trying to write a program where you're supposed to first create a person object, and afterwards be able to give that person different types of belongings. I'm putting each created person in an arraylist and every person is supposed to have their own inventory which is also an arraylist. I just don't understand how to add items to a specific persons arraylist and how to print that arraylist. Do I have to create a new instance of the arraylist 'belongings' every time I create a new person? and how do I access a certain persons arraylist? Appreciate any sort of feedback because I am super noob.
import java.util.ArrayList;
public class Sakregister extends Programskelett{
public static ArrayList<Person> personList = new ArrayList<Person>();
protected boolean nextCommand(){
String command = readString("> ").toLowerCase();
switch(command){
case "print list":
printAll();
System.out.println("Program is running");
break;
case "print person":
printUser();
System.out.println("Program is running");
break;
case "create item":
newItem();
break;
case "create user":
newUser();
break;
case "print richest":
printRichest();
System.out.println("Program is running");
break;
case "crash":
initCrash();
break;
case "quit":
System.out.println("Program has terminated");
return true;
default:
System.out.println("Not a valid command");
}
return false;
}
private void printAll() {
}
private void initCrash() {
for (Person thisPerson : personList) {
for (Item thisItem : thisPerson.belongings)
if (thisItem.name == "Stock"){
((Stock) thisItem).setStockCrash(0);
}
}
}
private void printRichest() {
}
private void newUser() {
System.out.println("enter name: ");
String name = keyboard.nextLine();
Person newPerson = new Person(name);
personList.add(newPerson);
System.out.println("Person added to list");
}
private boolean newItem() {
System.out.println("enter item type: ");
String itemType = readString("> ").toLowerCase();
switch(itemType){
case "trinket":
addTrinket();
break;
case "stock":
addStock();
break;
case "appliance":
addAppliance();
return true;
default:
System.out.println("Not a valid item type");
}
return false;
}
private void addAppliance() {
System.out.println("Enter name of appliance: ");
String appName = keyboard.nextLine();
System.out.println("Enter initial price: ");
int appInitialPrice = keyboard.nextInt();
System.out.println("Enter level of wear: ");
int appWear = keyboard.nextInt();
Appliance newAppliance = new Appliance(appName, appInitialPrice, appWear);
System.out.println("Enter name of owner: ");
Object owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newAppliance);
}
private void addStock() {
System.out.println("Enter name of stock entry: ");
String stockName = keyboard.nextLine();
System.out.println("Enter amount: ");
int stockAmount = keyboard.nextInt();
System.out.println("Enter price: ");
int stockPrice = keyboard.nextInt();
Stock newStock = new Stock(stockName, stockAmount, stockPrice);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
keyboard.nextLine();
for(Person entry : personList) {
if(entry.equals(owner)) {
entry.belongings.add(newStock);
}
}
}
private void addTrinket() {
System.out.println("Enter name of trinket: ");
String trinketName = keyboard.nextLine();
System.out.println("Enter number of gems: ");
int trinketGems = keyboard.nextInt();
System.out.println("Choose gold or silver: ");
String trinketMineral = keyboard.nextLine();
keyboard.nextLine();
Trinket newTrinket = new Trinket(trinketName, trinketGems, trinketMineral);
System.out.println("Enter name of owner: ");
String owner = keyboard.nextLine();
for(Person entry : personList)
if(entry.equals(owner))
entry.belongings.add(newTrinket);
}
private void printUser() {
// TODO Auto-generated method stub
}
protected void printMainMenu(){
System.out.println("Choose a command: ");
System.out.println("start");
System.out.println("quit");
}
public static void main(String[] args) {
Sakregister registerProgram = new Sakregister();
registerProgram.run();
}
}
public class Item{
protected String name;
public Item(String name){
this.name = name;
}
public String getItemName() {
return name;
}
import java.util.ArrayList;
public class Person{
public String name;
public String items;
public ArrayList<Item> belongings = new ArrayList<Item>();
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
public String toString() {
return "Name: " + name;
}
}
" I just don't understand how to add items to a specific persons arraylist and how to print that arraylist"
Your persons are in the personList, so i would use personList.get(n) to get the nth Person.
To add items to the belongings you can use personList.get(n).belongings.add(item).
To print an arraylist you can use a normal foreach loop:
for(Item i:personList.get(n).belongings){
System.out.println(i.getItemName());
}
Do I have to create a new instance of the arraylist 'belongings' every time I create a new person?
The ArrayList belongings is a field inside the Person class. When you create a person with the constructor all of its fields and variables are created in the memory. This happens every time you create a person, so every object (in your case person in the personList) has its own fields like the belongings list.
The new instance of the ArrayList<Item> belongings is already being created each time you create a new Person object, so you don't need to create it again anywhere. However, there is currently no getter for belongings, so you need to write one to access a given person's belongings. You want something like this:
public ArrayList<Item> getBelongings() {
return belongings;
}
You'll need to write a public method that accepts an Item object and adds it to the belongings of that Person. You shouldn't need help with writing another public method that calls System.out.println() on the belongings directly or iterates through them and prints them out.
I keeping running into this problem with my setInner method where if I keep it as telling me that "The method setInner(GList) in the type InnerList is not applicable for the arguments (Integer)". Which seems odd to me because it seems like an Integer would be applicable to a GList. Can someone help me figure out what I'm doing wrong?
My Inner Class where a list of integers 'inner' will be stored.
public class InnerList {
private String name;
private GList<Integer> inner = new GList<Integer>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GList<Integer> getInner() {
return inner;
}
public void setInner(GList<Integer> inner) {
this.inner = inner;
}
}
The portion of my public class that is causing me problems, within my main method:
GList<InnerList> list = new GList<InnerList>();
InnerList iList = new InnerList ();
Scanner sc = new Scanner(System.in);
String answer;
while (true) {
System.out.println("Do you want to enter a number (y/n)?");
answer = sc.nextLine();
if (answer.equals("y")) {
System.out.println("Enter Number: ");
answer = sc.nextLine();
try {
Integer num1 = Integer.valueOf(answer);
if (list.isEmpty() == true) {
iList.setInner(num1); //ERROR IS HERE
list.insertFirstItem(iList);
} else {
iList = new InnerList();
iList.setInner(num1); //AND HERE
list.insertNext(iList);
}
} catch (NumberFormatException e) {
System.out.println("You must enter an number! " + e);
}
continue;
} else {
break first;
}
}
The error message is a pretty clear. You are using
iList.setInner(num1);
when you should be doing
iList.setInner(myIntegerGlist);
to match the expected argument type of the method.