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));
Related
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();
}
}
//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 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)+
'}';
}
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);
}
}
}
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.