School Database in java - java

I was wondering if anyone had the time/patience to help me with this problem I'm having.
Basically all I'm trying to do is create a Very simple student database system and it doesn't seem to be working for me. This is my Main Class, Student Class and Subjects Class.
Subjects Class
import java.util.ArrayList;//ArrayList Import.
public class Subjects
{
/*(Public Variables)*/
public static String subjectName;
public static String subjectTutor;
public static ArrayList<Student> studentList = new ArrayList<Student>();
public static ArrayList<Student> mathsList = new ArrayList<Student>();
public static ArrayList<Student> excelList = new ArrayList<Student>();
public static ArrayList<Student> javaList = new ArrayList<Student>();
public static ArrayList<Student>classList= new ArrayList<Student>();
public Subjects(String sName)//If statement that will select the correct
tutor for the class
{
subjectName = sName;
if (subjectName == "maths")
{
subjectTutor= "Jennifer";
}
if (subjectName == "excel")
{
subjectTutor= "Ed";
}
if (subjectName == "java")
{
subjectTutor = "Brendan";
}
}
public static void printSubjectDetails()//Print Subject Details Method//Print the subject details listed below.
{
System.out.println("Subjects are " + subjectName + " and tutor is " + subjectTutor);
}
public static void printStudentList()
{
}
//Method for adding students to different classes
public static void addMathsStudent(Student localStudent)
{
mathsList.add(localStudent);
}
public static void addexcelStudent(Student localStudent)
{
excelList.add(localStudent);
}
public static void addStudent(Student localStudent)
{
studentList.add(localStudent);
}
public static void addjavaStudent(Student localStudent)
{
javaList.add(localStudent);
}
public static void printClass()//Print method that prints out the selected class when called in the main method.
{
System.out.println(subjectName + " Class List");
for(Student i : studentList)
{
Student.printStudent();
}
}
}
Student Class
import java.util.Scanner;//Scanner Import.
public class Student
{
//variables
public static String studentFName;
public static String studentLName;
int studentGrade;
public Student()
{
Scanner input = new Scanner(System.in);
//Operations for student class.
System.out.println("Please enter First Name.");
studentFName = input.next();
System.out.println("Please enter student Surname.");
studentLName = input.next();
}
//Print operations for student class.
public static void printStudent()
{
System.out.println("Students First Name is:" + studentFName);
System.out.println("Students Surname is:" + studentLName);
}
}
Main Class
import java.util.Scanner;
public class AppMenu {
// An Auto-generated method stub. (created when making the class.)
public static void main(String[] args)
{
appmenu();
}
public static <printClass> void appmenu()
{
Scanner input = new Scanner(System.in);
System.out.println(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<");
System.out.println("Enter [.1] to enroll a student");
System.out.println("Enter [.2] to View Class List");
System.out.println("Enter [.3] to Remove Students");
System.out.println("Enter [.4] to Clear Class Lists");
System.out.println("Enter [.5] to Exit The App");
System.out.println(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<");
//Case and Break.
String choice = input.next();
{
switch(choice)
{
case "1":
Student s1 = new Student();
System.out.println("What class would you like to enroll in?");
System.out.println("Press [.1] Enroll In Maths");
System.out.println("Press [.2] Enroll In Excel");
System.out.println("Press [.3] Enroll In Java");
System.out.println("Press [.4] Enroll In All of the above");
choice = input.next();
switch(choice)
{
case "1":
Subjects.addMathsStudent(s1);
appmenu();
break;
case "2":
Subjects.addexcelStudent(s1);
appmenu();
break;
case "3":
Subjects.addjavaStudent(s1);
appmenu();
break;
case "4":
Subjects.addStudent(s1);
appmenu();
}
case "2":
System.out.println("Press [.1] to View Maths Class List");
System.out.println("Press [.2] to View Excel Class List");
System.out.println("Press [.3] to View Java Class List");
choice = input.next();
switch(choice)
{
case "1":
Subjects.printSubjectDetails();
appmenu();
break;
case "2":
Subjects.printSubjectDetails();
appmenu();
break;
case "3":
Subjects.printSubjectDetails();
appmenu();
break;
case "4":
Subjects.printSubjectDetails();
appmenu();
break;
}
case "3":
System.out.println("Which student would you like to remove ");
Subjects.printStudentList();
Subjects.studentList();
}
}
}
}

Without running your code, your first problem is here...
public Subjects(String sName) {
subjectName = sName;
if (subjectName == "maths") {
subjectTutor = "Jennifer";
}
if (subjectName == "excel") {
subjectTutor = "Ed";
}
if (subjectName == "java") {
subjectTutor = "Brendan";
}
}
String comparison in Java is not done with == but is done with the String#equals method which means it should become...
public Subjects(String sName) {
subjectName = sName;
if ("maths".equals(subjectName)) {
subjectTutor = "Jennifer";
}
if ("excel".equals(subjectName)) {
subjectTutor = "Ed";
}
if ("java".equals(subjectName)) {
subjectTutor = "Brendan";
}
}
I'm not sure what this is suppose to be Subjects.studentList();, but I'd discourage you from trying to access the fields of an object/class directly and rely on appropriate management methods
Also,
switch (choice) {
case "1":
//...
case "2":
//...
case "3":
Has no break in it, which means if choice is 1, case 2 and 3 will also be executed...
Instead of relying on static, create a Subject class for each subject you want to manage and add students/tutors to each instance of the Subject, this will make the management much easier in the long run.
Case in point...
public class Student
{
//variables
public static String studentFName;
public static String studentLName;
This means that no matter how many instance of Student you create, they will all have the same first and last names...
Consider using some kind of loop to manage the menu menu rather the continuously calling appmenu, while it would take a very long time, you will eventually end up with a stack overflow exception...
Update with runnable example
This is the code I came up with when I was looking for other problems...
import java.util.ArrayList;
import java.util.Scanner;
public class AppMenu {
public static void main(String[] args) {
appmenu();
}
public static <printClass> void appmenu() {
Scanner input = new Scanner(System.in);
Subject maths = new Subject("Maths", "Jennifer");
Subject excel = new Subject("Excel", "Ed");
Subject java = new Subject("Java", "Brendan");
String choice = null;
do {
System.out.println(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<");
System.out.println("Enter [.1] to enroll a student");
System.out.println("Enter [.2] to View Class List");
System.out.println("Enter [.3] to Remove Students");
System.out.println("Enter [.4] to Clear Class Lists");
System.out.println("Enter [.5] to Exit The App");
System.out.println(">>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<");
//Case and Break.
choice = input.next();
{
switch (choice) {
case "1":
Student s1 = new Student();
System.out.println("What class would you like to enroll in?");
System.out.println("Press [.1] Enroll In Maths");
System.out.println("Press [.2] Enroll In Excel");
System.out.println("Press [.3] Enroll In Java");
System.out.println("Press [.4] Enroll In All of the above");
choice = input.next();
switch (choice) {
case "1":
maths.addStudent(s1);
break;
case "2":
excel.addStudent(s1);
break;
case "3":
java.addStudent(s1);
break;
case "4":
maths.addStudent(s1);
excel.addStudent(s1);
java.addStudent(s1);
}
break;
case "2":
System.out.println("Press [.1] to View Maths Class List");
System.out.println("Press [.2] to View Excel Class List");
System.out.println("Press [.3] to View Java Class List");
choice = input.next();
switch (choice) {
case "1":
maths.printSubjectDetails();
maths.printClass();
break;
case "2":
excel.printSubjectDetails();
excel.printClass();
break;
case "3":
java.printSubjectDetails();
java.printClass();
break;
case "4":
maths.printSubjectDetails();
maths.printClass();
excel.printSubjectDetails();
excel.printClass();
java.printSubjectDetails();
java.printClass();
break;
}
break;
case "3":
System.out.println("Which student would you like to remove ");
break;
}
}
} while (!"5".equals(choice));
}
public static class Subject {
/*(Public Variables)*/
public String subjectName;
public String subjectTutor;
public ArrayList<Student> studentList = new ArrayList<Student>();
public Subject(String sName, String tutor) {
subjectName = sName;
subjectTutor = tutor;
}
public void printSubjectDetails()//Print Subject Details Method//Print the subject details listed below.
{
System.out.println("Subjects are " + subjectName + " and tutor is " + subjectTutor);
}
public void addStudent(Student student) {
studentList.add(student);
System.out.println("Now have " + studentList.size() + " students for " + subjectName);
}
public void printClass()//Print method that prints out the selected class when called in the main method.
{
System.out.println(subjectName + " Class List");
for (Student i : studentList) {
i.printStudent();
}
}
}
public static class Student {
//variables
private String studentFName;
private String studentLName;
int studentGrade;
public Student() {
Scanner input = new Scanner(System.in);
//Operations for student class.
System.out.println("Please enter First Name.");
studentFName = input.next();
System.out.println("Please enter student Surname.");
studentLName = input.next();
}
//Print operations for student class.
public void printStudent() {
System.out.println("Students First Name is:" + studentFName);
System.out.println("Students Surname is:" + studentLName);
}
}
}

Related

Error with Checking availability of Getters and Setters in Java

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();
}
}

create arrayList including attribute from superclass and subclass

please help me
I have to create a 4 function using switch method. And I have a problem with function 3(show list of video and song)
For more details, I suppose I should create a class likes MultimediaManagerment. After that, I create an Arraylist in it and add all the attributes to this for printing the song like:
listOfMultimedia.add(songlist)
listOfMultimedia.add(videoList)
But the problem is the attribute "name" &"duration" are in the superclass Mutimedia while the attribute "singer" is in subclass Song. For that reason, from class MultimediaManagerment I can not add all the attribute to my arrayList.
Any ideas guys?
import java.util.*;
abstract class Multimedia{
String name;
double duration;
Scanner sc= new Scanner(System.in);
Multimedia(){
name=null;
duration=0;
};
void createMultimedia(){
System.out.print("\nEnter name: ");
name = sc.nextLine();
System.out.print("\nEnter duration: ");
duration=sc.nextDouble();
}
};
//Function Create Video
class Video extends Multimedia{
Video(){};
public void createVideo(){
System.out.println("----Enter video information----");
super.createMultimedia();
}
public String toString() {
return name + " " + duration ;
}
}
//Function Create Song
class Song extends Multimedia{
String singer;
Song(){
singer=null;
}
public void createSong(){
System.out.println("----Enter song information----");
System.out.print("Enter singer: " );
singer =sc.nextLine();
super.createMultimedia();
}
public String toString() {
return singer + " " + name + " " + duration ;
}
}
//Function show data
class MultimediaManagement extends Multimedia{
List<Multimedia> listOfMultimedia = new ArrayList<Multimedia>();
MultimediaManagement(){
listOfMultimedia=null;
}
void addMultimedia(Multimedia multimedia){
Multimedia ob = new Song(name, duration, singer); //ERROR
}
}
public class Assign801 {
public static void menu(){
Scanner sc= new Scanner(System.in);
int func;
Video video = new Video();
Song song = new Song();
do
{
System.out.println("Please choose function:\n1. Add a new Video\n2. Add a new Song\n3. Show all multimedia\n4.Exit");
func = sc.nextInt();
} while (func < 0 || func >4);
switch (func) {
case 1:
video.createVideo();
menu();
break;
case 2:
song.createSong();
menu();
break;
case 3: // show list of video & song
case 4: break;
}
}
public static void main(String[] args) {
menu();
}
}

How to print elements from linked list

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<>();
}
}
}

How to print the entries made in my LinkedList?

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));

how to access arraylist belonging to an object inside an arraylist

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.

Categories

Resources