array in object oriented programming - java

I'm a beginner in object-oriented programming and this is my first little project.I've heard that here everyone can help you in your code and this is my first time.Anyway, my problem why array doesn't store any value?
Here is the code:
public class Information {
private IT_Members[] member= new IT_Members[10];
private int counter = 0;
Information()
{
for ( int ctr=0;ctr<member.length;ctr++)
{
member[ctr] = new IT_Members ();
}
}
public void Add(IT_Members member)
{
if(counter<10)
{
this.member[counter].setName(member.getName());
this.member[counter].setDeparment(member.getDeparment());
this.member[counter].setPostion(member.getPostion());
this.member[counter].setID(member.getID()+counter);
counter++;
}
else
System.out.println("Add List Full");
}
public void Display()
{
if (counter!=0)
{
for (int ctr=0;ctr<10;ctr++){
System.out.println(this.member[ctr].getName()+
this.member[ctr].getDeparment()+
this.member[ctr].getPostion()+
this.member[ctr].getID());
}
}
else
System.out.println("No member yet!");
}
Here is the Main class:
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
IT_Members input1 = new IT_Members();
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
.........................................................................
public class IT_Members {
private String name,deparment,postion;
private int ID=1000;
private int Flag=0;
IT_Members (){
}
IT_Members (String name, String deparment , String postion ,int ID , int Flag){
this.name= name;
this.deparment=deparment;
this.postion=postion;
this.ID=ID;
this.Flag=Flag;
}
public String getName (){
return this.name;
}
public String getDeparment (){
return this.deparment;
}
public String getPostion (){
return this.postion;
}
public int getID (){
return this.ID;
}
public int getFlag (){
return this.Flag;
}
public void setName (String name){
this.name = name;
}
public void setDeparment (String Deparment){
this.deparment = deparment;
}
public void setPostion (String postion){
this.postion = postion;
}
public void setID (int ID){
this.ID = ID;
}
public void setFlag (int Flag){
this.Flag = Flag ;
}
public String toStu()
{
String str = "";
str = "\nName: " + this.name +
"\nDeparment: " + this.deparment +
"\nPostion: " + this.postion +
"\nID: " + this.ID;
return str;
}
}
Please, I'm stuck with this I appreciate any help.
Thanks.

You never call the Add function in the Information class. Therefore you never initialize any of the array elements you then want to display.
You need to add input2.Add(input1) before you print that is has been added.

You have to create every time a new Object and in the end you have to add in the list.
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
IT_Members input1 = new IT_Members();// this need to be here so that every time crete new object
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
input2.Add(input1); // that was missing
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}

Related

Creating an printing an object that stores strings and integers in java

I have the following problem. Five classes are interacting with each other. Two of theme are doing fine. But with the creating of an Object of one class (Ticket) in my main class Event (getting user input from another class (UserInput), an processing this in the costructor) i have now problem to display the results.
Main class Event with main methode
import java.util.ArrayList;
public class Event {
private static String artistName;
private static int artistSalary;
private Language language;
private static ArrayList<String> trackList;
private InputReader inputReader;
private Ticket ticket;
private int amountOfTicketCategories;
private static Object[] ticketList;
private static int index;
public Event() {
}
public Event(Artist artist, Ticket ticket) {
artistName = artist.getArtistName();
artistSalary = artist.getArtistSalary();
trackList = artist.getArrayList();
for (index = 0; index < amountOfTicketCategories; index++) {
ticketList[index] = ticket.getTicket();
ticketList[index].toString();
}
}
public void chooseWhatToDefine() {
language = new Language();
language.whatToSpecify();
}
public void setTicketPrice(String ticketCategory, int ticketPrice) {
}
public void displayArtist(String artistName, int artistSalary) {
language = new Language();
language.displayArtistAndSalary(artistName, artistSalary);
}
public void displayTracklist(ArrayList<String> trackList) {
language = new Language();
language.displayTrackList(trackList);
}
public void displayTickets(Object[] ticketList) {
language = new Language();
language.displayTicket(ticketList);
}
public static void main(String[] args) {
Event event1 = new Event(new Artist(), new Ticket());
event1.displayArtist(artistName, artistSalary);
event1.displayTracklist(trackList);
event1.displayTickets(ticketList);
}
}
Ticket class with constructor that initalize the class with the user input comming from the InputReader class, and creates an object of Strings and Integers.
import java.util.Arrays;
public class Ticket {
private static String ticketCategory;
private static int ticketAmount;
private static int ticketPrice;
private InputReader inputReader;
private int amountOfTicketCategories;
private int index;
private Ticket[] ticketList;
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
}
public Ticket() {
inputReader = new InputReader();
inputReader.specifyTicketCategories();
ticketList = new Ticket[amountOfTicketCategories];
for (index = 0; index < amountOfTicketCategories; index++) {
inputReader.specifyTicket(ticketCategory, ticketAmount, ticketPrice);
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
}
}
public String toString() {
return("TicketCategory: " + ticketCategory + "Amount of Tickets: " + ticketAmount + "Ticket Price: " +ticketPrice);
}
public Object getTicket() {
return ticketList[index];
}
public int getAmountOfTicketCategories() {
amountOfTicketCategories = inputReader.specifyTicketCategories();
return amountOfTicketCategories;
}
}
InptReader class that processes the user input:
import java.util.ArrayList;
import java.util.Scanner;
public class InputReader {
private Scanner sc;
private Language language;
private ArrayList <String> tracks;
public InputReader() {
tracks = new ArrayList<String>();
language = new Language();
sc = new Scanner(System.in);
}
public int specifyTicketCategories() {
language.defineAmountOfTicketCategories();
return sc.nextInt();
}
public void specifyTicket(String ticketCategory, int ticketAmount, int ticketPrice) {
language.specifyTicketCategory();
ticketCategory = sc.next();
language.specifyTicketAmount();
ticketAmount = sc.nextInt();
language.specifyTicketPrice();
ticketPrice = sc.nextInt();
}
public int amountOfTickets() {
return sc.nextInt();
}
public int ticketPrice() {
return sc.nextInt();
}
public String readName() {
language.specifyArtist();
return sc.nextLine();
}
public int readInteger() {
language.specifyArtistSalary();
return sc.nextInt();
}
public void addTitle() {
int anzahlSongs = 3;
int index = 0;
while (index < anzahlSongs) {
language.specifyTrackList();
tracks.add(sc.nextLine());
index++;
}
}
public ArrayList<String> getArray() {
return tracks;
}
}
Language class that consists of the language statements
import java.util.ArrayList;
public class Language {
public Language () {
}
public void whatToSpecify() {
System.out.println("What would you like to specify fist? For Artist press 1, for Ticket press 2");
}
public void specifyArtist() {
System.out.println("Who is the artist? ");
}
public void specifyArtistSalary() {
System.out.println("How much does the artist earn? ");
}
public void displayTicket(Object[] ticketList) {
System.out.println("Ticketlist: " + ticketList);
}
public void displayArtistAndSalary(String artistName, int artistSalary) {
System.out.println("Artist: " + artistName + " " + "Salary: " + artistSalary);
}
public void displayTrackList(ArrayList<String> trackList) {
System.out.println("Tracklist: " + trackList);
}
public void specifyTicketCategory() {
System.out.println("What is the ticket category? ");
}
public void specifyTicketAmount() {
System.out.println("What ist the amount of tickets? ");
}
public void specifyTicketPrice() {
System.out.println("What is the price for your ticket?");
}
public void specifyTrackList() {
System.out.println("Add title: ");
}
public void defineAmountOfTicketCategories() {
System.out.println("How many ticket categories you like to set up?");
}
public void line() {
System.out.println("***********************************");
}
}
Artist class that that has creates an instance of an artist in the main class (same idea as for ticket) but with other variables and parameters.
import java.util.ArrayList;
public class Artist {
private int artistSalary;
private String artistName;
private InputReader inputReader;
ArrayList <String> trackList;
public Artist() {
inputReader = new InputReader();
artistName = inputReader.readName();
artistSalary = inputReader.readInteger();
inputReader.addTitle();
trackList = inputReader.getArray();
trackList.remove(2);
}
public String getArtistName() {
return artistName;
}
public int getArtistSalary() {
return artistSalary;
}
public ArrayList<String> getArrayList(){
return trackList;
}
}
Output in the console:
Add title:
Hello
Add title:
Hello
How many ticket categories you like to set up?
5
Artist: David Salary: 5000
Tracklist: [, Hello]
Ticketlist: null
First of all, in the Ticket class's constructor, you use the other constructor (The one with the 3 arguments), which has an empty body.
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
//this is empty
}
That means you're creating an object with.. nothing in it (null variables).
Try this:
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
this.ticketCategory = ticketCategory;
this.ticketAmount = ticketAmount;
this.ticketPrice = ticketPrice;
}
Then, your getTicket method is wrong. You never define the "index" integer in your Ticket class.
public Object getTicket() {
return ticketList[index];
}
Where "index" is undefined.
The ticketList should not be in the Ticket class => each time you create a Ticket instance, it will probably not be the same as the previous one.

Return user input into setter function

I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}

Cannot find symbol in Java application

I am working on a simple text-based rpg battler program as an introduction to Java. I seem to have a decent understanding of the majority of code, but I have ran into a couple of issues.
The issues I am having are in the Project class.
In my switch statement I am trying to use the setSpells() and setArrows() methods and I am getting a "cannot find symbol" error message. I realize that this is probably due to something I have set up incorrectly in the sub-classes, but I am unsure what that is.
The second issue is in the print statement pulling the character name by use of c.getName(). The c part of that statement gives the same error message.
Is there something simple that I am misunderstanding in these situations? Any help resolving this would be appreciated. Thank you.
Here is my main project class file:
package project;
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
Character c = new Wizard();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setSpells(10);
break;
}
case "elf":
{
Character c = new Elf();
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Here is my Character class:
package project;
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character()
{
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name)
{
this.name = name;
}
public String getName(){
return name;
}
public void setGold(int gold)
{
this.gold = gold;
}
public int getGold()
{
return gold;
}
public void setHealth(int health)
{
this.health = health;
}
public int getHealth()
{
return health;
}
#Override
public String toString()
{
return "Name: " + name + "\n" +
"Gold: " + gold + "\n" +
"Health: " + health + "\n";
}
public static int getCount()
{
return count;
}
public abstract String getDisplayText();
}
Here is my Wizard sub-class:
package project;
public class Wizard extends Character {
private int spells;
public Wizard()
{
super();
spells= 0;
count++;
}
public void setSpells(int spells)
{
this.spells= spells;
}
public int getSpells(){
return spells;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Spells: " + spells+ "\n";
}
}
And finally my Elf sub-class:
package project;
public class Elf extends Character{
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
}
When you create one of your Characters...
Character c = new Elf();
You are downcasting the instance to "act" like Character, this is very useful feature in Object Oriented Programming, but is causing you issues in this case, as Character does not have the methods you are looking for.
Instead, start by assigning the class to a concrete version of the instance...
Elf elf = new Elf();
Apply the properties you need and then assign it to a Character reference...
Character c = null;
//...
switch (classChoice) {
//...
case "elf":
{
Elf elf = new Elf();
//...
c = elf;
}
}
c = elf;
for example...
Have a look at the section on Polymorphism for more details
Your issue is with these lines
Character c = new Wizard();
....
Character c = new Elf();
The character class itself doesn't have the setFireballs or SetArrows methods. You need to define the object as a wizard or elf in order to get access to said methods... EG:
Elf c = new Elf();
Wizard c = new Wizard();
etc
Character c = new Wizard();
Character has neither a setFireBalls method nor a setArrows method.
I have made the some changes to your code..
here is the final code.
package h;
import java.util.Scanner;
public class he {
public static void main(String[] args) {
System.out.println("Welcome to Lands of the Sun\n");
Character c = new Wizard();
Character e = new Elf();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Please choose your class (wizard or elf): \n");
String classChoice = sc.next();
sc.nextLine();
System.out.print("Please choose a name for your " + classChoice + ": ");
String charName = sc.next();
sc.nextLine();
int healthVal = (int) (Math.random() * 10) + 1;
switch (classChoice) {
case "wizard":
{
c.setName(charName);
c.setGold(25);
c.setHealth(healthVal);
c.setFireballs(10);
break;
}
case "elf":
{
;
e.setName(charName);
e.setGold(25);
e.setHealth(healthVal);
e.setArrows(10);
break;
}
}
System.out.print(c.getName());
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Wizard class
public class Wizard extends Character {
private int fireballs;
public Wizard()
{
super();
fireballs = 0;
count++;
}
public void setFireballs(int fireballs)
{
this.fireballs = fireballs;
}
public int getFireballs(){
return fireballs;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Fireballs: " + fireballs + "\n";
}
#Override
public void setArrows(int i) {
}
}
Elf class
public class Elf extends Character {
private int arrows;
public Elf()
{
super();
arrows = 0;
count++;
}
public void setArrows(int arrows)
{
this.arrows = arrows;
}
public int getArrows(){
return arrows;
}
#Override
public String getDisplayText()
{
return super.toString() +
"Arrows: " + arrows + "\n";
}
#Override
public void setFireballs(int i){
}
}
abstract class Character
public abstract class Character {
private String name;
private int gold;
private int health;
public static int count = 0;
public Character() {
name = "";
gold = 0;
health = 0;
}
public Character(String name, int gold, int health) {
this.name = name;
this.gold = gold;
this.health = health;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setGold(int gold) {
this.gold = gold;
}
public void setHealth(int health) {
this.health = health;
}
public int getHealth() {
return health;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Gold: " + gold + "\n" + "Health: "
+ health + "\n";
}
public static int getCount() {
return count;
}
public abstract String getDisplayText();
public abstract void setFireballs(int i);
public abstract void setArrows(int i);
}
hope this helps...

A java array of objects

I have an assignment where I have to create three classes, a client class that performs all I/O, a catalog class that maintains a list of catalogItem objects and a catalogItem class that defines a single item in the store's catalog.
I'm trying to start simple at first and create the array and make sure that it is accepting data before I move on to the rest of the assignment. I was able to compile it with no issues but when I am trying to display the array, I get nothing.
import java.util.Scanner;
public class lab3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Catalog catalog = new Catalog();
boolean endCatalog = false;
while (!endCatalog)
{
System.out.println("Please choose and option: \n"
+ "1 - Display all items of the catalog\n"
+ "2 - Display an item by keyword\n"
+ "3 - Add an item to the catalog\n"
+ "4 - Remove an item from the catalog\n"
+ "5 - Change the cost of one item in the catalog\n"
+ "6 - Change the cost of all items in catalog by percent\n"
+ "7 - Exit");
int choice = in.nextInt();
switch (choice) {
case 1: System.out.println(catalog.displayAll()); break;
case 2: System.out.println("Display keyword"); break;
case 3: System.out.println("Add item:\nEnter ID: ");
int newId=in.nextInt();
System.out.println("Enter description: ");
String newDesc=in.next();
System.out.println("Enter cost: ");
double newCost=in.nextDouble();
catalog.add(newId, newDesc, newCost); break;
case 4: System.out.println("Remove item"); break;
case 5: System.out.println("Change cost of one item"); break;
case 6: System.out.println("Change cost by %"); break;
case 7: endCatalog=true; break; }
}
}
}
class Catalog
{
final static int MAX = 100;
private CatalogItem[] catalogItems;
int inUse;
public Catalog()
{
catalogItems=new CatalogItem[MAX];
}
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
/*public void remove(int id)
{
}
public String find(String keyword)
{
}
public void changeCost(int id, double percent)
{
}
public void increaseCost(double percent)
{
}
public String toString()
{
}
public boolean equals(Catalog obj)
{
}*/
public String displayAll()
{
String str = "";
for (int i=0; i<inUse; i++) {
str = str + "\n" + catalogItems[i]; }
return str;
}
}
class CatalogItem
{
private int itemID;
private String description;
private double cost;
public CatalogItem()
{
itemID = 1;
description = " ";
cost = 0.0;
}
public CatalogItem(int newID, String newDesc, double newCost)
{
itemID = newID;
description = newDesc;
cost = newCost;
}
public int getItemID()
{
return itemID;
}
public void setItemID(int newID)
{
itemID=newID;
}
public String getDescription()
{
return description;
}
public void setDescription(String newDesc)
{
description=newDesc;
}
public double getCost()
{
return cost;
}
public void setCost(double newCost)
{
cost=newCost;
}
public String toString()
{
return itemID + ", " + description + ", " + cost;
}
public boolean equals(CatalogItem obj)
{
return false;
}
}
Here's the problem:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
What happens to newItem after it is created?
You call this method to add the catalog item:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
But as we can see, this doesn't actually do anything with the object it creates. Did you mean to have this overload of add() call the other one? That would be a good design.
Also, in the other version of add(), you do this:
inUse = 0;
Since you reset inUse every time add() is called, your array will never contain more than one item. Do you see why this is? You should just take this line out.
There is not items ever added to:
private CatalogItem[] catalogItems;
That is so, because you call only this method:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
And that one will never call method that actually tries to add something to the array:
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
In the long run that method will also not work, because item is always added to the index 0. That is so, because as first thing you always set: inUse = 0.

JAVA Linked List Confused on why I can't check a variable against an node in the Linked List?

public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) { //WHY IS THIS ASKING FOR SEPARATE METHOD?
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
I am trying to take an input and check to see if that input is in the Linked List. I am having problems though getting this to work right.
If I add the new method in my LinkedList.Java class it says it needs to define a variable for link. Below is what I have in entirety if it helps:
import java.util.Scanner;
class airline {
public static LinkedList list = new LinkedList();
public static void main(String[] args) {
list.addAirplane("Allen",501);
list.addAirplane("James",501);
list.addAirplane("Andrea",501);
list.addAirplane("Velvett",501);
list.addAirplane("Paul",501);
//Method sort the list after year the car was made
list.sortList();
menu();
//Method to print all objects in List
System.out.println(list.viewAll());
}
public static void menu(){
int menuOpt;
System.out.println("Airline Menu:");
System.out.println("1. Reserve a Ticket");
System.out.println("2. Cancel Reservations");
System.out.println("3. Check Reservations");
System.out.println("4. Display Airplanes on Flights");
Scanner input = new Scanner(System.in);
menuOpt=input.nextInt();
System.out.println(menuOpt);
switch (menuOpt){
case 1:
System.out.println("Reserve a Ticket");
reserveTick();
break;
case 2:
System.out.println("Cancel Reservations");
cancel();
break;
case 3:
System.out.println("Check Reservations");
check();
break;
case 4:
System.out.println("Passengers listed by Flights");
break;
default:
System.out.println("INVALID RESPONSE!");
menu();
break;
}
}
public static void reserveTick(){
String name;
System.out.println("Enter Customer Name to RESERVE ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.addAirplane(name,501);
System.out.println(name + " has been added to Flight Number 501");
menu();
}
public static void cancel(){
String name;
System.out.println("Enter Customer Name to CANCEL ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.remove(name, 501);
System.out.println(name + " has been REMOVED from Flight Number 501");
menu();
}
public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) {
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
else {
System.out.println(name + " is not on this Flight!");
menu();
}
}
public static void listpassengers(){
list.sortList();
}
}
------------------------------------------------------------------
import java.util.*;
public class LinkedList
{
private AirplaneNode head = null;
public void addAirplane(String name , int hk)
{
//If head = null then create the first node
if(head == null)
{
head = new AirplaneNode(name,hk,null);
}
else
{
//If there are more than 1 node
head = new AirplaneNode(name,hk,head);
}
}
public void sortList()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(AirplaneNode cursor = head ; cursor.getNext() != null ; cursor = cursor.getNext())
{
if(cursor.getHk() < cursor.getNext().getHk())
{
String n = cursor.getName();
int hk = cursor.getHk();
cursor.setName(cursor.getNext().getName());
cursor.setHk(cursor.getNext().getHk());
cursor.getNext().setName(n);
cursor.getNext().setHk(hk);
sorted = false;
}
}
}
}
public String viewAll()
{
StringBuffer str = new StringBuffer();
for(AirplaneNode cursor = head ; cursor != null ; cursor = cursor.getNext())
{
str.append(cursor+"\n");
}
return new String(str);
}
}
--------------------------------------------------------------
public class AirplaneNode
{
private String name;
private int hk;
private AirplaneNode next;
public AirplaneNode(String name,int hk,AirplaneNode head)
{
this.name = name;
this.hk = hk;
this.next = head;
}
public AirplaneNode getNext()
{
return next;
}
public String getName()
{
return name;
}
public int getHk()
{
return hk;
}
public void setName(String in)
{
name = in;
}
public void setHk(int in)
{
hk = in;
}
public String toString()
{
return name + " " + hk ;
}
}
It seems as if you are creating a own class LinkedList in the top package here:
import java.util.*;
public class LinkedList
{
Since your method check() belongs in the airline class in the same package (and without any import of java.util.LinkedList) it will instead use the class you have created and that class doesn't implement any contains() method.
Declare your linked list this way:
public static LinkedList<String> list = new LinkedList<String>();
EDIT (based on your comment):
It looks like you want a list of flights, where each flight has a list of passenger names.
public class Flight implements Comparable<Flight> {
private List<String> mPassengers;
private final int mFlight;
private static final Collator sCollator = Collator.getInstance();
public Flight(int flight) {
mPassengers = new ArrayList<String>();
mFlight = flight;
}
public void sortPassengers() {
Collections.sort(mPassengers, sCollator);
}
public void addPassenger(String name) {
mPassengers.add(name);
}
public boolean removePassenger(String name) {
return mPassengers.remove(name);
}
public boolean hasPassenger(String name) {
return mPassengers.contains(name);
}
public String getFlight() { return mFlight; }
public int compareTo(Flight other) {
return mFlight - other.mFlight;
}
}
public static List<Flight> list = new LinkedList<Flight>();
public static void main(String[] args) {
Flight flight = new Flight(501);
flight.addPassenger("Allen");
// etc. for all flight 501 passengers
list.add(flight);
// repeat all the above for each flight number
}
You should be able to fill in the rest.

Categories