this is my first time posting on StackOverflow so I am still getting used to the format. I apologize in advance. Over here, I have 2 classes FruitBasket and FruitBasketUtility. I've included the getters and setters method in the Fruitbasket.Java. Everything compiled fine but I got an error:
Fail 1 -- test11addToBasketMethodToAddOneFruitBasketObject::
Check the availability (or) the signature of addToBasket/getFruitBasketList in the FruitBasketUtility class or Setters and Getters in FruitBasket class
Main.Java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
//For reading input from user
Scanner in = new Scanner(System.in);
//Creating object of FruitBasketUtility
FruitBasketUtility fruitBasketUtility = new FruitBasketUtility();
int choice;
do{
//Displaying the menu
System.out.println("Select an option:");
System.out.println("1. Add Fruit to Basket");
System.out.println("2. Calculate Bill");
System.out.println("3.Exit");
//Reading the choice
choice = in.nextInt();
in.nextLine();
switch(choice){
case 1:
//Reading fruit details from user
System.out.println("Enter the fruit name");
String fruitName = in.next();
in.nextLine();
System.out.println("Enter weight in Kgs");
int weightInKgs = in.nextInt();
in.nextLine();
System.out.println("Enter price per Kg");
int pricePerKg = in.nextInt();
in.nextLine();
FruitBasket fruit = new FruitBasket(fruitName, weightInKgs, pricePerKg);
//Adding fruit to basket
fruitBasketUtility.addToBasket(fruit);
break;
case 2:
//Calculating and showing the bill
ArrayList<FruitBasket> basket = fruitBasketUtility.getFruitBasketList();
if(basket.size() > 0){
System.out.println("The estimated bill amount is Rs " + fruitBasketUtility.calculateBill((basket.stream())));
}
else{
System.out.println("Your basket is empty. Please add fruits.");
}
break;
case 3:
System.out.println("Thank you for using the application.");
break;
default:
System.out.println("Invalid option. Please try again.");
break;
}
}while(choice != 3);
}
}
FruitBasket.Java
public class FruitBasket {
//Member variables
String fruitName;
int weightInKgs;
int pricePerKg;
//Getters and setters
public void setFruitName(String fruitName){
this.fruitName =fruitName;
}
public void setWeightInKgs(int weightInKgs){
this.weightInKgs =weightInKgs;
}
public void setPricePerKg(int pricePerKg){
this.pricePerKg =pricePerKg;
}
public String getFruitName(){
return fruitName;
}
public int getWeightInKgs(){
return weightInKgs;
}
public int getPricePerKg(){
return pricePerKg;
}
//An empty constructor
public FruitBasket(){
fruitName = "";
weightInKgs = 0;
pricePerKg = 0;
}
//Three argument constructor
public FruitBasket(String fruitName, int weightInKgs, int pricePerKg){
this.fruitName = fruitName;
this.weightInKgs = weightInKgs;
this.pricePerKg = pricePerKg;
}
}
FruitBasketUtility.Java
import java.util.ArrayList;
import java.util.stream.Stream;
public class FruitBasketUtility {
//Member variables
ArrayList<FruitBasket> fruitBasketList;
//Getters and setters
public void setFruitBasketList(ArrayList<FruitBasket> fruitBasketList){
this.fruitBasketList = fruitBasketList;
}
public ArrayList<FruitBasket> getFruitBasketList(){
return fruitBasketList;
}
//Constructor
public FruitBasketUtility(){
fruitBasketList = new ArrayList<>();
}
//Add to basket
public void addToBasket(FruitBasket fObj){
fruitBasketList.add(fObj);
}
//Calculte the bill using stream of FruitBasket
public int calculateBill(Stream<FruitBasket> fruitBasketStream){
return fruitBasketStream.mapToInt(x -> x.getPricePerKg() * x.getWeightInKgs()).sum();
}
}
Related
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<>();
}
}
}
//Main :
package DevAyo;
import java.util.Scanner;
public class Main {
private static Scanner scanner =new Scanner(System.in);
private static Album Alb =new Album("Kamikaze");
public static void main(String[] args) {
boolean quit = true;
while (quit){
System.out.println("Choose actions : ");
System.out.println("\t\t 1.Add new Songs to Album :");
System.out.println("\t\t 2.printSongs");
System.out.println("\t\t 3.Quit");
System.out.println("choose Action : ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice){
case 1:
AddSong();
break;
case 2:
Alb.printSongs();
break;
case 3:
quit=false;
break;
}
}
}
public static void AddSong(){
// System.out.println("Insert Album Name: ");
// String albumName =scanner.nextLine();
System.out.println("Pleas Enter Number of Songs :");
int Number = scanner.nextInt();
for (int i=0;i<Number;i++){
System.out.println("Enter Song Name "+(i+1)+": ");
String name=scanner.nextLine();
scanner.nextLine();
System.out.println("Enter Singer of Song "+(i+1)+": ");
String SingerName =scanner.nextLine();
System.out.println("Enter Song "+(i+1)+" released Day: ");
String ReleasedDay = scanner.nextLine();
System.out.println("Enter Length of the Song"+(i+1)+": ");
int SongLength=scanner.nextInt();
Songs song = Songs.creatSong(name,SingerName,ReleasedDay,SongLength);
if(Alb.addSOngs(song))
System.out.println("Songs added ! ");
else
System.out.println("Error ! ");
}
}`enter code here`
}
//Album Class
package DevAyo;
import java.util.ArrayList;
import java.util.Scanner;
public class Album {
public String AlbumName;
private static Scanner scanner = new Scanner(System.in);
ArrayList<Songs> ListofSongs;
public Album(String albumName) {
AlbumName = albumName;
this.ListofSongs=new ArrayList<Songs>();
}
public boolean addSOngs(Songs song){
if(findSong(song.getSongName())>=0){
System.out.println("Songs aLready Exisit ! ");
return false;
}
ListofSongs.add(song);
return true;
}
private int findSong(String songName){
for(int i=0; i<ListofSongs.size();i++){
Songs song = ListofSongs.get(i);
if(song.getSongName().equals(songName)){
return i;
}
}
return -1;
}
public void printSongs(){
for(int i=0;i<this.ListofSongs.size();i++){
System.out.println("Song Name: "+ this.ListofSongs.get(i).getSongName()+"\n"
+"Singer: "+this.ListofSongs.get(i).getSongSinger()+"\n"+"Song Released Day: "+this.ListofSongs.get(i).getSongDay()+
"\n"+"Song Length: "+this.ListofSongs.get(i).songLength+" min");
}
}
}
//Songs Class
package DevAyo;
public class Songs {
public static String songName;
public static String songSinger;
public static String songDay;
public static int songLength;
public Songs(String songName, String songSinger, String songDay, int songLength) {
this.songName = songName;
this.songSinger = songSinger;
this.songDay = songDay;
this.songLength = songLength;
}
public String getSongName() {
return this.songName;
}
public String getSongSinger() {
return this.songSinger;
}
public String getSongDay() {
return this.songDay;
}
public int getSongLength() {
return this.songLength;
}
public static Songs creatSong(String name, String singerName, String releasedDay, int songLength){
return new Songs(songName,songSinger,songDay,songLength);
}
}
i just tried so many was i can't undrestand why it displlays null , i 've created the constructor in both classes and still dosen't seem to work, honestly i've searched the internet about the problem but it's says that i should add constructor i've add them but nothing happpen anyway hope the code is clear , hope you guys can help thanks .
After a Scanner.nextInt(); leaves an empty line so the next time you call Scanner.nextLine(); it will give you that empty line.
If you want to avoid this, you could do one of this 2 options:
Parse
Always use Scanner.nextLine() and cast to the type of variable you want.
Example: int a = Integer.parseInt(scanner.nextLine());
Read that empty line
always you use the nextInt() immediately call nextLine()
Example:
int a = scanner.nextInt();
scanner.nextLine()
I need help concerning my coursework in Java Programming. I am creating a console Flower (shop) application which stores the flower's name, colour, age and price. However, I am having problems printing the LinkedList I created to store records of the Flowers added. I have tried tweaking with the showFlowers method in the Test class for a while now and nothing is working. I'd appreciate the help, thanks. Here's my code.
Flower Class
public class Flower {
//variables
private String name; //name of flower
private String colour; //colour of flower
private int age; //age of flower (days)
private double price; //price of flower
public Flower(String n, String c, int a, double p) {
this.name = n;
this.colour = c;
this.age = a;
this.price = p;
}
public void getName() {
System.out.println("Name: " + this.name);
}
public void getColour() {
System.out.println("Colour: " + this.colour);
}
public void getAge() {
System.out.println("Age (Days): " + this.age);
}
public void getPrice() {
System.out.println("Price: " + this.price);
}
public void getFullDetails(){
System.out.println("Name: " + this.name);
System.out.println("Colour: " + this.colour);
System.out.println("Age (Days): " + this.age);
System.out.println("Price: " + this.price);
}
}
FlowerTest Class
package flower;
import java.util.LinkedList;
import java.util.Scanner;
public class FlowerTest {
private static LinkedList<Flower> myFlowers = new LinkedList();
public static void firstMenu() {
System.out.println("<------------ Welcome to the Flower Menu -------------->");
System.out.println("1. Add Flower Details");
System.out.println("2. Show All Flowers");
System.out.println("3. Exit");
System.out.println("Enter choice: ");
}
public static void mainMenu() {
for (;;) {
firstMenu();
Scanner inputScanner = new Scanner(System.in);
int choice = inputScanner.nextInt();
switch (choice) {
case 1:
createFlower(inputScanner);
break;
case 2:
showFlowers(inputScanner);
break;
case 3:
System.out.println("Goodbye");
System.exit(0);
break;
default:
//error handling
System.err.println("Unrecognized option");
break;
}
}
}
public static Flower createFlower(Scanner in) {
System.out.println("<-------- Adding Flower ---------->");
System.out.println("Input Flower Name: ");
String name = in.next();
System.out.println("Input Flower Colour: ");
String colour = in.next();
System.out.println("Input Flower Age (Days): ");
int age = in.nextInt();
System.out.println("Input Flower Price: ");
double price = in.nextDouble();
return new Flower(name, colour, age, price);
}
public static void showFlowers(Scanner in){
for (Flower flower : myFlowers) {
flower.getFullDetails();
}
}
public static void main(String[] args) {
mainMenu();
}
}
It appears like your code is never adding any flowers to your myFlowers List. Your createFlower() method simply returns the newly-created Flower object, but the return value is never used in your switch statement.
You should either make the createFlower() method void and have it add the flower to your List directly, or let it return the flower, and have the handling code in the switch statement add it to the List.
Change:
createFlower(inputScanner)
to:
myFlowers.add(createFlower(inputScanner));
I have a Enum Class, a Player Class, and a class called Lisa that extends Player class. Im trying to randomly generate a value (PAPER, ROCK, or SCISSORS) from the Enum. Error: "The primitive type int of Roshambo does not have a field ROCK." Any advice or pointers would be greatly appreciated. It may be apparent, but this is my fists Java class and Google and Stackoverflow searches have not helped. Here is what I have coded so far:
UPDATE: Thanks for all the assistance. I've updated my whole program below. I was wondering if anyone could suggest the best way/place possible to implement logic to determine the winner/loser of the game? Here is the full code:
MAIN
package gameOfRoshambo;
import java.util.Scanner;
public class RoshamboApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Roshambo!");
System.out.println("Enter your name:");
//Create a new payer
Player1 player1 = new Player1();
String name = sc.nextLine();
player1.setName(name);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
System.out.println("Hello " + name + ". " + "Would you like to play against Bart or Lisa? (B/L)");
String opponent = sc.next();
if(opponent.equalsIgnoreCase("B")){
//Create a new Bart opponent
Bart bart = new Bart();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Bart: " + bart.getRoshambo());
}
else if (opponent.equalsIgnoreCase("L")){
//Create a new Lisa opponent
Lisa lisa = new Lisa();
System.out.println(player1.getName() + ": " + player1.getChoice());
System.out.println("Lisa: " + lisa.getRoshambo());
}
// Ask user if they want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
//Close Scanner
System.out.println("Thanks for playing! Goodbye!");
sc.close();
}
}
ENUM
package gameOfRoshambo;
public enum Roshambo
{ROCK, PAPER, SCISSORS;
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: throw new IllegalArgumentException();
}
}
}
PLAYER
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
PLAYER1
package gameOfRoshambo;
import java.util.Scanner;
public class Player1 extends Player{
String player1 = "";
public Player1(){
super();
}
Scanner scan = new Scanner(System.in);
public Roshambo getChoice(){
System.out.println("Enter Choice: Paper, Rock, Scissors (r/p/s): ");
char playerChoice = scan.nextLine().toUpperCase().charAt(0);
switch (playerChoice){
case 'R':
return Roshambo.ROCK;
case 'P':
return Roshambo.PAPER;
case 'S':
return Roshambo.SCISSORS;
}
System.out.println("Invalid input!");
return getChoice();
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
BART
package gameOfRoshambo;
public class Bart extends Player {
public Bart(){
super();
}
public Roshambo getRoshambo(){
return Roshambo.ROCK;
}
#Override
int generateRoshambo() {
// TODO Auto-generated method stub
return 0;
}
}
LISA
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int shoot = rand.nextInt(3);
return Roshambo.values()[shoot];
}
#Override
int generateRoshambo() {
return 0;
}
}
You should store your roshambo field as a Roshambo not an int and update your setter and getter accordingly. This is because in Java Enums cannot be casted to int. See the below stack overflow link for explanation:
Cast Int to enum in Java
Field names should start with a lower case
Use Roshambo.values()[choice]
Get rid of the 1 + in 1 + rand.nextInt(3); because the nextInt() method has the first enum value in position 0. So
Roshambo.values()[0] = ROCK
Roshambo.values()[1] = PAPER
Roshambo.values()[2] = SCISSORS
In the Lisa constructor, change to rand = new Random() instead of Random rand = new Random() to avoid assigning to a new local variable which you lose once the constructor finishes
See the code snippets I've attached below for you
Player Class
package gameOfRoshambo;
abstract class Player {
String name;
Roshambo roshambo;
abstract int generateRoshambo();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Roshambo getRoshambo() {
return roshambo;
}
public void setRoshambo(Roshambo newRoshambo) {
roshambo = newRoshambo;
}
}
Lisa Class
package gameOfRoshambo;
import java.util.Random;
public class Lisa extends Player {
private Random rand;
public Lisa(){
super();
rand = new Random();
}
public Roshambo getRoshambo(){
int choice = rand.nextInt(3);
return Roshambo.values()[choice];
}
#Override
int generateRoshambo() {
return 0;
}
}
Also with the new above implementation you don't use the abstract int generateRoshambo() method so consider removing it and its implementation in Lisa...
Your field Roshambo is of type int. I think you want to declare it as something more like this:
Roshambo roshambo;
It is bad practice to capitalize field names. In this case, it confused you because you mixed up the field name with the type. You will have to replace int with Roshambo in several other places in your code.
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.