Java - Building an Array of Objects using Scanner - java

I'm attempting to build an Array of Objects using input from the user. My code is running without error but the output pane is blank and says 'Build Successful' I can't work out what I have done wrong because I am sure all the code is correct. Any pointers would be most appreciated. Thank you in advance
package sanctuary;
import java.util.Scanner;
/**
*
* #author dell
*/
public class Sanctuary {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
class Animal
{
private String species;
private String animalname;
private String breed;
private double weight;
private String gender;
private int age;
private String location;
private String vet;
private double vaccine;
private double medicine;
private double food;
private double muandv;
void GetAnimalData() // Defining GetAnimalData()
{
Scanner sc = new Scanner(System.in);
System.out.print("\n\tEnter Animal Species : ");
species = (sc.nextLine());
System.out.print("\n\tEnter Animal Name : ");
animalname = sc.nextLine();
System.out.print("\n\tEnter Animal Breed : ");
breed = (sc.nextLine());
System.out.print("\n\tEnter Animal Weight : ");
weight = (sc.nextDouble());
System.out.print("\n\tEnter Animal Gender : ");
gender = (sc.nextLine());
System.out.print("\n\tEnter Animal Age : ");
age = Integer.parseInt(sc.nextLine());
System.out.print("\n\tEnter Animal Location : ");
location = (sc.nextLine());
System.out.print("\n\tEnter Vet Name: ");
vet = (sc.nextLine());
System.out.print("\n\tEnter Vaccine Cost : ");
vaccine = (sc.nextDouble());
System.out.print("\n\tEnter Medicine Cost : ");
medicine = sc.nextDouble();
System.out.print("\n\tEnter Food Cost : ");
food = (sc.nextDouble());
System.out.print("\n\tEnter Maintenance, Utility and Vet Cost : ");
muandv = (sc.nextDouble());
}
void PrintAnimalData() // Defining PrintAnimalData()
{
System.out.print("\n\t" + species + "\t" +animalname + "\t" +breed + "\t" +weight + "\t" +gender + "\t" +age + "\t" +location + "\t" +vet + "\t" +vaccine + "\t" +medicine + "\t" +food + "\t" +muandv);
}
public void main(String args[])
{
Animal[] AnimalList = new Animal[100];
int i = 0;
for(i=0;i<AnimalList.length;i++)
AnimalList[i] = new Animal(); // Allocating memory to each object
for(i=0;i<AnimalList.length;i++)
{
System.out.print("\nEnter details of "+ (i+1) +" Animal\n");
AnimalList[i].GetAnimalData();
}
System.out.print("\nAnimal Details\n");
for(i=0;i<AnimalList.length;i++)
AnimalList[i].PrintAnimalData();
}
}
}
}

Your main method doesn't do anything: it just contains declarations.

First case is to make an parametrized constructor for access to the private data- for writing
package stackoverflow.foo.sanctuary;
public class AnimalParametrizedConstructor {
private String name;
private String desc;
public AnimalParametrizedConstructor(String name, String desc) {
super();
this.name = name;
this.desc = desc;
}
//when no getters, that is the only way how to access to class fields for print outside
#Override
public String toString() {
return "name: " + this.name + ", description: " + this.desc;
}
}
Second way is to properly generate getters and setter for specific fields
package stackoverflow.foo.sanctuary;
public class AnimalGettersSetters {
private String name;
private String desc;
AnimalGettersSetters(){
//this is implicit constructor in java, you dont need to define it
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Then you can call printing method from outside of the class anywhere you want (method must to be public), or to use getters for obtaining their values.
For writing you can use parametrized constuctor in first case, or setters in second case.
Please, notice that you have to create new object instance in both of cases when you want to fill the array- AnimalParametrizedConstructor[] paramAnimals = new AnimalParametrizedConstructor[COUNT]; is just a declaration, not creating the instances (otherwise you will got nullpointer exception)
package stackoverflow.foo.sanctuary;
import java.util.Scanner;
public class SanctuaryMainClassWhateverName {
public static void main(String[] args) {
final int COUNT = 2;
Scanner sc = new Scanner(System.in);
// parametrized constructor section
// load animals with parametrized constructor
AnimalParametrizedConstructor[] paramAnimals = new AnimalParametrizedConstructor[COUNT];
for (int i = 0; i < COUNT; i++) {
System.out.println("What a name?");
String name = sc.nextLine();
System.out.println("What a description?");
String desc = sc.nextLine();
AnimalParametrizedConstructor newAnimal = new AnimalParametrizedConstructor(name, desc);
paramAnimals[i] = newAnimal;
}
// and print them- because we defined toString, we have access to fields without
// getter
for (int i = 0; i < paramAnimals.length; i++) {
System.out.println("animal no. " + i + ": " + paramAnimals[i].toString());
}
// animals with getter and setter section
AnimalGettersSetters[] animalsGS = new AnimalGettersSetters[COUNT];
for (int i = 0; i < COUNT; i++) {
AnimalGettersSetters newGS = new AnimalGettersSetters();
// load
System.out.println("What a name?");
newGS.setName(sc.nextLine()); // we have setters to private fields!
System.out.println("What a description?");
newGS.setDesc(sc.nextLine()); // we have setters to private fields!
animalsGS[i] = newGS;
}
// print using gettes
for (int i = 0; i < COUNT; i++) {
System.out.println(
"animal no." + i + ": name: " + animalsGS[i].getName() + ", desc: " + animalsGS[i].getDesc());
}
// NEVER FORGET !
sc.close();
}
}
Honestly, you should to look for some OOP tutorials for beginning.

Your mistake is that you have node added any executable code in your public static void main(String args[]), thus program does not show any output.
import java.util.Scanner;
public class Sanctuary {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
class Animal
{
private String species;
private String animalname;
private String breed;
private double weight;
private String gender;
private int age;
private String location;
private String vet;
private double vaccine;
private double medicine;
private double food;
private double muandv;
void GetAnimalData() // Defining GetAnimalData()
{
Scanner sc = new Scanner(System.in);
System.out.print("\n\tEnter Animal Species : ");
species = (sc.nextLine());
System.out.print("\n\tEnter Animal Name : ");
animalname = sc.nextLine();
System.out.print("\n\tEnter Animal Breed : ");
breed = (sc.nextLine());
System.out.print("\n\tEnter Animal Weight : ");
weight = (sc.nextDouble());
System.out.print("\n\tEnter Animal Gender : ");
gender = (sc.nextLine());
System.out.print("\n\tEnter Animal Age : ");
age = Integer.parseInt(sc.nextLine());
System.out.print("\n\tEnter Animal Location : ");
location = (sc.nextLine());
System.out.print("\n\tEnter Vet Name: ");
vet = (sc.nextLine());
System.out.print("\n\tEnter Vaccine Cost : ");
vaccine = (sc.nextDouble());
System.out.print("\n\tEnter Medicine Cost : ");
medicine = sc.nextDouble();
System.out.print("\n\tEnter Food Cost : ");
food = (sc.nextDouble());
System.out.print("\n\tEnter Maintenance, Utility and Vet Cost : ");
muandv = (sc.nextDouble());
}
void PrintAnimalData() // Defining PrintAnimalData()
{
System.out.print("\n\t" + species + "\t" +animalname + "\t" +breed + "\t" +weight + "\t" +gender + "\t" +age + "\t" +location + "\t" +vet + "\t" +vaccine + "\t" +medicine + "\t" +food + "\t" +muandv);
}
public void main(String args[])
{
}
}
Animal[] AnimalList = new Animal[100];
int i = 0;
for(i=0;i<AnimalList.length;i++)
AnimalList[i] = new Animal(); // Allocating memory to each object
for(i=0;i<AnimalList.length;i++)
{
System.out.print("\nEnter details of "+ (i+1) +" Animal\n");
AnimalList[i].GetAnimalData();
}
System.out.print("\nAnimal Details\n");
for(i=0;i<AnimalList.length;i++)
AnimalList[i].PrintAnimalData();
}
}

Related

object of class inherited from abstract class return null values from getters [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have a abstract class name, abstract class mammal which is descendant of animal class, and class Lion, which is descendant of mammal. Then I have class ZooManager, I can add animals, edit animals, show all animals etc through simple console app. I have all instances saved in ArrayList.My problem is when I try to get attributes of Lion for example, I always get null. I was trying to make getters abstract in animals and then use them in Lion, but didnt work. I can remove the instance by index from ArrayList, but cant use any getter. What should I do? Thank you.
Animal class
abstract public class Animal {
protected String name;
protected int birth;
protected float amount;
protected String food;
public Animal(String name, int birth, float amount, String food) {
this.name = name;
this.birth = birth;
this.amount = amount;
this.food = food;
}
public Animal() {
}
public abstract String howToFeed();
public abstract String howToCare();
public String getName() {
return this.name; };
public int getBirth() {
return this.birth;
}
public float getAmount() {
return this.amount;
}
public String getFood() {
return this.food;
}
}
Lion class
public class Lion extends Mammal {
public Lion(String name, int birth, float amount, String food) {
super(name, birth, amount, food);
}
public Lion() {
super();
}
public String howToFeed() {
return "Lion " + name + " needs " + amount + " kg of " + food + " per day";
}
public String howToCare() {
return "Lion is an animal";
}
#Override
public String toString() {
return "Lion{" +
"name='" + name + '\'' +
", birth=" + birth +
", amount=" + amount +
", food='" + food + '\'' +
'}';
}
}
And this is ZooManager class. The part I am talking about is in the removeAnimal method and listOfAnimals method
import java.util.Scanner;
import java.util.ArrayList;
public class ZooManager {
public ArrayList<Animal> animals;
public ZooManager() {
this.animals = new ArrayList<Animal>();
}
Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------ ZOO ------------------");
System.out.println("1) Add an new animal");
System.out.println("2) Remove an existing animal");
System.out.println("3) Show all animals");
System.out.println("4) Edit animal");
System.out.println("5) Show animal functions ");
System.out.println("6) End manager");
System.out.println("------------------ ZOO ------------------");
}
private static void groupMenu(){
System.out.println("1) Mammal");
System.out.println("1) Fish");
System.out.println("1) Bird");
}
private static void animalMenu(int group){
if (group == 1) {
System.out.println("1) Lion");
System.out.println("2) Bear");
} else if (group == 2){
System.out.println("1) Salmon");
System.out.println("2) Goldfish");
} else {
System.out.println("1) Eagle");
System.out.println("2) Owl");
}
}
private void addAnimal() {
Animal[][] className = {{new Lion()}, {new Eagle()}};
groupMenu();
System.out.println("Choose a group: ");
int group = sc.nextInt();
animalMenu(group);
int animal = sc.nextInt();
System.out.println("Name: ");
sc.nextLine();
String nameX = sc.nextLine();
System.out.println("Year of birth: ");
int birthX = sc.nextInt();
System.out.println("Amount of food per day: ");
float amountX = sc.nextFloat();
System.out.println("Type of food: ");
sc.nextLine();
String foodX = sc.nextLine();
animals.add(className[group - 1][animal - 1]);
System.out.println(nameX);
manager();
}
private void removeAnimal() {
System.out.println("Type index of animal you want to remove");
int index = sc.nextInt();
String nameX = animals.get(index).getName();
animals.remove(index);
manager();
}
public void manager(){
mainMenu();
int input = sc.nextInt();
if (input == 1) {
addAnimal();
} else if (input == 2){
removeAnimal();
} else if (input == 3) {
listOfAnimals();
} else if (input == 4) {
editAnimal();
} else {
System.out.println("Ending manager");
}
}
private void listOfAnimals(){
System.out.println(" index |name |birth |amount |food");
for (Animal item: animals) {
System.out.println(animals.indexOf(item) + " |" + item.getName() + " |" + item.getBirth() + " |" + item.getBirth() + " |" + item.getFood());
}
manager();
}
private void editAnimal(){
System.out.println("Index of animal u want to edit: ");
int index = sc.nextInt();
sc.nextLine();
System.out.println("1) Name");
System.out.println("2) Birth");
System.out.println("3) Amount");
System.out.println("4) Food");
System.out.println("Type number: ");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1 -> {
System.out.println("Type new name: ");
animals.get(index).name = sc.nextLine();
}
case 2 -> {
System.out.println("Type new year of birth: ");
animals.get(index).birth = sc.nextInt();
}
case 3 -> {
System.out.println("Type new amount: ");
animals.get(index).amount = sc.nextFloat();
}
case 4 -> {
System.out.println("Type new food: ");
animals.get(index).food = sc.nextLine();
}
}
System.out.println("done");
manager();
}
}
Update: Here is Mammal class, but for now its just copy of animal
abstract public class Mammal extends Animal{
public Mammal(String name, int birth, float amount, String food) {
super(name, birth, amount, food);
}
public Mammal() {
}
}
*Edit
The problem is here
private void addAnimal() {
Animal[][] className = {{new Lion()}, {new Eagle()}};
You create those animals without any value in their member fields. Therefore later when you read the field value is null.
Your method could be
private void addAnimal() {
groupMenu();
System.out.println("Choose a group: ");
int group = sc.nextInt();
animalMenu(group);
int animal = sc.nextInt();
System.out.println("Name: ");
sc.nextLine();
String nameX = sc.nextLine();
System.out.println("Year of birth: ");
int birthX = sc.nextInt();
System.out.println("Amount of food per day: ");
float amountX = sc.nextFloat();
System.out.println("Type of food: ");
sc.nextLine();
String foodX = sc.nextLine();
Animal[][] className = {{new Lion(namex, birthx, amountx, foodx)},
{new Eagle(namex, birthx, amountx, foodx)}};
animals.add(className[group - 1][animal - 1]);
System.out.println(nameX);
manager();
}

Need help making ArrayList

I am trying to create an ArrayList using at least six Person objects that will contain user inputted name and age resulting in information being printed out in alphabetical order.
Array list that contains person:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Categorization
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
System.out.println("Please enter a name " + name); // Can't return values
String nameEntry = input.toString();
System.out.println("Please enter an age " + age);
int ageEntry = input.nextInt();
}
}
I am unfamiliar with creating classes and feel like this is where most of my errors occur.
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
Tried to return name and age but they are not going back to the Public Class
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
}
You can try this:
public class Categorization {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
for(int i=1; i<=6; i++) {
System.out.print("Please enter name for person " + i + " : ");
String nameEntry = input.next();
System.out.print("Please enter an age for person " + i + " : ");
int ageEntry = input.nextInt();
Person obj = new Person(nameEntry, ageEntry);
people.add(obj);
}
System.out.println("List of entries you entered: ");
for(Person obj: people) {
System.out.println("Name: " + obj.getName() + " " + "Age: " + obj.getAge());
}
}
}
Output:
You need to create a Person object using new keyword to store respective values and then finally add it to the people list.

My program is printing only the last input from the ArrayList

I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.

Constructor error with encapsulation

I have my code in 3 different files using encapsulation (Data hiding) and i have 1 problem at the very end of my code in my if and else statement (very bottom) when trying to call the classes from the other 2 documents. I will put the code in 1st document to 3rd document. Any suggestions on what I did wrong?
// FIRST DOCUMENT
public class CollegeCourse { //class name
//variables
String deptName;
int courseNum;
int credits = 3;
double fee;
//constructor
public CollegeCourse(String department, int course, int Credits) {
deptName = department;
courseNum = course;
credits = Credits;
fee = credits * 120;
}
//getters setters
public String getdepartment() {
return deptName;
}
public String setdepartment(String dept) {
return dept = deptName;
}
public int getcourse() {
return courseNum;
}
public int setcourse(int c) {
return c = courseNum;
}
public int getCredits() {
return credits;
}
public int setCredits(int cred) {
return cred = credits;
}
public void display()
{
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//SECOND DOCUMENT
public class LabCourse extends CollegeCourse { //polymorphism extending CollegeCourse class into LabCourse class.
//constructor
public LabCourse(String department, int course, int Credits){
//add 50 dollars to the fee
super(department, course, Credits);
fee = fee + 50;
}
//display the course
public void display(){
System.out.print("This course is a lab course" + fee);
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//THIRD DOCUMENT MAIN HEADER
import java.util.Scanner;
public class UseCourse {
public static void main(String[] args){
String s, c, cd;
Scanner input = new Scanner(System.in);
System.out.print("Enter: BIO, CHEM, ENG, MATH: ");
s = input.nextLine();
System.out.print("What is the course number: ");
c = input.nextLine();
System.out.print("How many credits: ");
cd = input.nextLine();
if(s.equals ("BIO") || s.equals ("CHEM")){
LabCourse lc = new LabCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
lc.display();
}
else {
CollegeCourse cc = new CollegeCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
cc.display();
}
}
}
Here is the error that i'm getting.
UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);
^
And it repeats for each error "department, course, Credits"
UseCourse.java:29: error: cannot find symbol
CollegeCourse cc = new CollegeCourse(department, course, Credits);
^
Your parameters in your constructor call are all wrong. Neither department, course or Credits are defined, so you would need to use s, c and cd instead, as those are the variables you're using for your input.
Furthermore, you need to read c and cd as integers and pass those to your constructor as follows:
System.out.print("What is the course number: ");
int c = input.nextInt();
System.out.print("How many credits: ");
int cd = input.nextInt();
// ...
LabCourse lc = new LabCourse(s, c, cd);

object array index value is being overided by the preceding index value

This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}

Categories