Hi I'm working on a java program that allows user to input their information such as name, car model, capacity etc, later they can see their information in a list:
Car Registration Listing
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1001 John Wayne 111111111 ABC123 Blue 2010 Toyota Vios 1.5
1002 Bea Arthur 222222222 WEA888 Red 2010 Nissan Teana 2.0
1003 Meg Ryan 333333333 PBL168 Black 2011 Honda City 1.6
1004 Jane Doe 444444444 BBB777 White 2011 Nissan Teana 2.0
1005 Al Johnson 555555555 CAT118 Green 2012 Toyota Vios 1.5
1006 Ned Beatty 666666666 TV798 Blue 2012 Toyota Vios 1.5
Below is the code:
public class CarRegistrationListing {
int regNo;
String name;
int icNo;
String plateNo;
String color;
int year;
String make;
String model;
double capacity;
public CarRegistrationListing(int regNo, String name, int icNo, String plateNo, String color, int year, String make, String model, double capacity) {
this.regNo = regNo;
this.name = name;
this.icNo = icNo;
this.plateNo = plateNo;
this.color = color;
this.year = year;
this.make = make;
this.model = model;
this.capacity = capacity;
}
public int getRegNo() {
regNo++;
return regNo;
}
public String getName(){
return name;
}
public int getIcNo(){
return icNo;
}
public String getPlateNo(){
return plateNo;
}
public String getColor(){
return color;
}
public int getYear(){
return year;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public double getCapacity(){
return capacity;
}
public void setName(String name){
this.name = name;
}
public void setIcNo(int icNo){
this.icNo = icNo;
}
public void setPlateNo(String plateNo){
this.plateNo = plateNo;
}
public void setColor(String color){
this.color = color;
}
public void setYear(int year){
this.year = year;
}
public void setMake(String make){
this.make = make;
}
public void setModel(String model){
this.model = model;
}
public void setCapacity(double capacity){
this.capacity = capacity;
}
#Override
public String toString() {
return "CarRegistrationListing{" + "regNo=" + regNo + ", name=" + name + ", icNo=" + icNo + ", plateNo=" + plateNo + ", color=" + color + ", year=" + year + ", make=" + make + ", model=" + model + ", capacity=" + capacity + '}';
}
}
This is for test run:
import java.util.Scanner;
public class TestCarReg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many records do you want to register: ");
int record = scan.nextInt();
CarRegistrationListing car = new CarRegistrationListing(1000, "", 0, "", "", 0, "", "", 0.0);
for (int i = 0; i < record; i++) {
String[] carType = {"Toyota Vios", "Nissan Teana", "Honda City"};
System.out.println("Car Type:");
for (String carType1 : carType) {
System.out.println(carType1);
}
System.out.print("Choose your car type(1 to 3): ");
int type = scan.nextInt();
String make;
String model;
switch (type) {
case 1:
make = "Toyota";
model = "Vios";
break;
case 2:
make = "Nissan";
model = "Teana";
break;
default:
make = "Honda";
model = "City";
break;
}
System.out.print("Enter name: ");
String name = scan.nextLine();
car.setName(name);
scan.nextLine();
System.out.print("Enter IC number: ");
int icNo = scan.nextInt();
car.setIcNo(icNo);
System.out.print("Enter plate number: ");
String plateNo = scan.next();
car.setPlateNo(plateNo);
System.out.print("Enter color: ");
String color = scan.next();
car.setColor(color);
System.out.print("Enter year: ");
int year = scan.nextInt();
car.setYear(year);
car.setMake(make);
car.setModel(model);
System.out.print("Enter capacity: ");
double capacity = scan.nextDouble();
car.setCapacity(capacity);
}
System.out.println("Car Registration Listing");
for (int i = 0; i < record; i++) {
System.out.println("Reg No.\tName\t\tIC No.\tPlate No.\tColor\tYear\tMake\tModel\tCapacity");
System.out.println(car.getRegNo() + "\t" + car.getName() + "\t\t" + car.getIcNo() + "\t" + car.getPlateNo() + "\t\t" + car.getColor() + "\t" + car.getYear() + "\t" + car.getMake() + "\t" + car.getModel() + "\t" + car.getCapacity());
}
}
}
I tried printing the output according to the sample shown above, but I got this in my output:
debug: How many records do you want to register: 2
Car Type: Toyota Vios Nissan Teana Honda City
Choose your car type(1 to 3): 1
Enter name: william Sebastian
Enter IC number: 1111
Enter plate number:AC1212
Enter color: Red
Enter year: 2010
Enter capacity: 1.0
Car Type: Toyota Vios Nissan Teana Honda City
Choose your car type(1 to 3): 1
Enter name: wong ang soon
Enter IC number: 2222
Enter plate number: AR1234
Enter color: White
Enter year: 2013
Enter capacity: 2.0
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1001 2222 AR1234 White 2013 Honda City 2.0
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1002 2222 AR1234 White 2013 Honda City 2.0
The name can't be printed and the variables for first person were disappeared, I tried to use array for CarRegistrationListing but it caused error.
I would appreciate if someone can point out my mistakes.
Thank you so much!
the variables for first person were disappeared
It is because the variable car is overwritten inside the for loop every time when you enter a new entry.
To show the values for first person, you can create an ArrayList before the data-entry for loop
List<CarRegistrationListing> carList = new ArrayList<CarRegistrationListing>();
And store the values into the ArrayList at the end of for loop
carList.add(car);
At last, you may print the values from ArrayList as below.
System.out.println("Reg No.\tName\t\tIC No.\tPlate No.\tColor\tYear\tMake\tModel\tCapacity");
for (CarRegistrationListing car : carList) {
System.out.println(car.getRegNo() + "\t" + car.getName() + "\t\t" + car.getIcNo() + "\t" + car.getPlateNo() + "\t\t" + car.getColor() + "\t" + car.getYear() + "\t" + car.getMake() + "\t" + car.getModel() + "\t" + car.getCapacity());
}
The name can't be printed
It is because the newline character is not consumed by nextInt() causing input not properly read, you can add scan.nextLine() before reading the name from input.
You may find more information from here, as mentioned by #user16320675 in the comments
scan.nextLine();
String name = scan.nextLine();
I also noticed you would like to have autoincrement for RegNo.
Instead of adding regNo++ in getter function, I will suggest to create a static member for generating unique regNo inside Constructor
More information at: Java create a unique ID for each instantiated object using instance methods instead of class/static methods
static int globalRegNo = 1000;
public CarRegistrationListing(int regNo, String name, int icNo, String plateNo, String color, int year, String make, String model, double capacity) {
this.regNo = globalRegNo++;
this.name = name;
this.icNo = icNo;
this.plateNo = plateNo;
this.color = color;
this.year = year;
this.make = make;
this.model = model;
this.capacity = capacity;
}
Related
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();
}
}
So the while loop is not working, even though it compiles. How do I position it correctly??
I tried a few things but they kinda worked. if someone on here can help me out that would be great
import java.util.Scanner;
//This is a Driver program to test the external Class named Student
public class StudentDriver //BEGIN Class Definition
{
//**************** Main Method*************************
public static void main (String[] args)
{Scanner scan = new Scanner(System.in);
//Data Definitions:
//Instance Data
String courseName;
int courseCredits;
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
//Executable Statements:
//Initialize first Student
name = "Fred Fergel";
id = "0123";
street = "123 Main Street";
city = "Smalltown";
state = "NY";
zip = "12345";
major = "Computer Science";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
//Test toString
System.out.println("Student 1\n\n" + student1.toString());
//Print a blank line
System.out.println();
//Add a course
student1.addCourse("CSC111", 4);//NOTE: DO NOT PUT A SPACE BETWEEN CSC AND 111
//Print schedule
System.out.println("Student 1's Schedule:\n\n");
student1.displaySchedule();//call method
final String FLAG = "Y";
String prompt = "Y";
while (prompt.equals("y"))
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);
System.out.println("Do you wish to enter another course? y/n");
prompt = scan.next();
}
//end while
}//end main
}//end StudentDriver
Here is the student class:
import java.util.Scanner;
public class Student
{Scanner scan = new Scanner(System.in);
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int SIZE = 6;
final int MAX_CREDITS = 18;
String [ ] schedule = new String [SIZE];
int courseNumber = 0; //start out with no courses
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 10 courses
{
System.out.println("You have exceeded 10 courses.");
}//end courseNumber
}//addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
}
String prompt = "Y";
while (prompt.equals("y"))
Y and y are not the same thing. You need to use .equalsIgnoreCase() instead of .equals() if you want it to ignore case.
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.
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);
I have searched for this question and I am still at a loss after trying alot. I am completely new to Java so please excuse the ignorance. I am trying to read in a file from the scanner. The file contains SmartPhone attributes and I would like to assign them directly to the smartphone class variables and then create my phone and add it to the list. However, the phones are not getting added and I have made sure that the text file is in the format that the scanner and class attributes are expecting. Can anyone spot my mistake?
package model;
import java.io.*;
import java.util.*;
public class menu {
public static void main(String[] args) {
int inputOption;
SmartPhone newPhone;
LinkedList<SmartPhone> phoneList;
FileToLinkedList smartphoneList;
smartphoneList = new FileToLinkedList();
phoneList = smartphoneList.createDatabase();
System.out.println(phoneList);
Scanner userInput = new Scanner(System.in);
//userInput.useDelimiter(System.getProperty("line.separator"));
int smartphoneLabel = 0;
String model = "";
String manufacturer = "";
int year = 0;
double price = 0.0;
String color = "";
System.out.println("==============================");
System.out.println(" SmartPhone Database Menu ");
System.out.println("==============================");
System.out.println("Options: ");
System.out.println(" 1. Display all smartphones ");
System.out.println(" 2. Add a smartphone ");
System.out.println(" 3. Delete a smartphone ");
System.out.println(" 4. Search for a smartphone ");
System.out.println(" 5. Quit ");
System.out.println("==============================");
inputOption = KeyIn.inInt("Please select an option from the menu: ");
switch(inputOption){
case 1:
System.out.println("You've selected to display the entire smartphone database.");
break;
case 2:
System.out.println("You have chosen to add a smartphone to the database. ");
System.out.println("Smartphone Label: ");
smartphoneLabel = userInput.nextInt();
System.out.println("Model: ");
model = userInput.next();
System.out.println("Manufacturer: ");
manufacturer = userInput.next();
System.out.println("Year: ");
year = userInput.nextInt();
System.out.println("Price: ");
price = userInput.nextDouble();
System.out.println("Color: ");
color = userInput.next();
newPhone = new SmartPhone(smartphoneLabel, model, manufacturer, year, price, color);
phoneList.add(newPhone);
System.out.println("Here is your new database of smartphones. ");
//phoneList.displayDatabase();
break;
case 3:
System.out.println("You have chosen to delete a smartphone from the database. ");
break;
case 4:
System.out.println("You have chosen to search for a particular model." );
break;
case 5:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid selection.");
break;
}
}
}
package model;
import java.io.*;
import java.util.*;
public class FileToLinkedList extends LinkedList {
LinkedList<SmartPhone> myPhoneList;
public FileToLinkedList(){
myPhoneList = new LinkedList<SmartPhone>();
}
public LinkedList<SmartPhone> createDatabase(){
try{
Scanner scanner = new Scanner("SmartPhone_Database.txt");
while(scanner.hasNext()) {
SmartPhone newPhone = new SmartPhone();
newPhone.setLabel(scanner.nextInt());
newPhone.setModel(scanner.nextLine());
newPhone.setManufacturer(scanner.nextLine());
newPhone.setYear(scanner.nextInt());
newPhone.setPrice(scanner.nextDouble());
newPhone.setColor(scanner.nextLine());
//phoneList.add(newPhone);
((LinkedList<SmartPhone>)myPhoneList).add(newPhone);
}
}
catch(InputMismatchException e){}
return myPhoneList;
}
}
*I have listed two ways that have been suggested, one commented out--but still nothing..
package model;
import java.lang.*;
public class SmartPhone {
private int smartphoneLabel;
private String model;
private String manufacturer;
private int year;
private double price;
private String color;
//constructor
public SmartPhone(){
smartphoneLabel = 0;
model = "";
manufacturer = "";
year = 0;
price = 0.0;
color = "";
}
public SmartPhone(int myLabel, String myModel, String myManufacturer, int myYear, double myPrice, String myColor)
{
smartphoneLabel = myLabel;
model = myModel;
manufacturer = myManufacturer;
year = myYear;
price = myPrice;
color = myColor;
}
public int getLabel(){
return smartphoneLabel;
}
public String getModel(){
return model;
}
public String getManufacturer(){
return manufacturer;
}
public int getYear(){
return year;
}
public double getPrice(){
return price;
}
public String getColor(){
return color;
}
public void setLabel(int label){
smartphoneLabel = label;
}
public void setModel(String model){
model = model;
}
public void setManufacturer(String manufacturer){
manufacturer = manufacturer;
}
public void setYear(int year){
year = year;
}
public void setPrice(double price){
price = price;
}
public void setColor(String color){
color = color;
}
public void display(){
System.out.println("Label: " + getLabel() + "\n");
System.out.println("Model: " + getModel() + "\n");
System.out.println("Manufacturer: " + getManufacturer() + "\n");
System.out.println("Year: " + getYear() + "\n");
System.out.println("Price: " + getPrice() + "\n");
System.out.println("Color: " + getColor() + "\n");
}
}
And this is my text file:
1234 NC2000 Nokia 2009 100.00 Silver
3874 CT4500 iPhone 2012 450.00 White
59780 F5600 Android 2012 475.00 Black
5983 T95000 Android 2011 500.00 Silver
23300 GH3000 Samsung 2010 275.00 Black
47000 TT2700 Samsung 2009 100.00 Silver
Your problem is in your return statement for createDatabase(). You only return a LinkedList when there is an InputMismatchException, when you want to return myPhoneList every single time the method is called. That should fix things right up for you.