Java Object Array printing null? - java

I have 3 classes, Movie which is used to add Movie objects to an in MovieDatabase but it keeps printing null.
When I add 2 Movies its like the first Movie is erased and it prints null instead. Also is there a way to check if the position in the array is empty and not print if it is empty?
Here is my Movie class
public class Movie {
private String name;
private String director;
private double fileSize;
private int duration;
private int moviecount;
public Movie()
{
name = null;
director = "";
fileSize = 0;
duration = 0;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDirector(String newDirector)
{
director = newDirector;
}
public String getDirector()
{
return director;
}
public void setfileSize(double newfileSize)
{
fileSize = newfileSize;
}
public double getfileSize()
{
return fileSize;
}
public void setDuration(int newDuration)
{
duration = newDuration;
}
public int getDuration()
{
return duration;
}
and here my MovieDatabase class:
public class MovieDatabase
{
private Movie[] mov;
private int i;
public int count=0;
public MovieDatabase()
{
mov = new Movie[4];
i=0;
}
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
public void printNames()
{
for (int i = 0; i < mov.length; i++)
{
System.out.println(mov[i].getName());
}
}
}
import java.util.*;
public class Interface {
Scanner console = new Scanner(System.in);
MovieDatabase m = new MovieDatabase();
private void run()
{
int option;
do{
System.out.print("Add Movie(0), Delete Movie(2),Show Movies(3),Movie Count(4) \n");
option = console.nextInt();
switch(option)
{
case 0: addMovie();
break;
case 3: printMovies();
break;
}
}
while(option!=9);
}
public static void main(String[] args){
Interface intFace = new Interface();
intFace.run();
}
public void addMovie()
{
String name, director;
double fileSize;
int duration;
System.out.println("Movie Name: ");
name = console.next();
System.out.println("Movie Director: ");
director = console.next();
System.out.println("Movie File Size: ");
fileSize = console.nextDouble();
System.out.println("Movie Duration: ");
duration = console.nextInt();
System.out.print("Movie Added!");
m.addData(name,director,fileSize,duration);
}
public void printMovies()
{
m.printNames();
}
}
I tried to include only the relevant parts but majority of what I have done so far is relevant.

The problem is in these lines
....
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
...
Each and every time you're adding a new data, you're erasing all previous records by assigning new movie object to every element in array. This erases all previous data.
You should instead move these 2 lines in MovieDatabase constructor. Or a better option would be to initialize them when you're setting data.
...
public void addData(String name, String director, double fileSize, int duration)
{
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i] = new Movie(); //++ edit
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
...
Also is there a way to check if the position in the array is empty and not print if it is empty?
You can create a method in Movie class which checks whether this movie object is empty or not and returns appropriate result.
public class Movie {
...
...
public boolean isEmpty() {
if(
this.name.isEmpty() &&
this.director &&
this.fileSize == 0 &&
this.duration == 0 &&
this.moviecount == 0
)
return true;
else
return false;
}
...
...
}
Now you can check whether this movie object is empty or not using:
if(mov[i].isEmpty()) {
//empty movie object
...
}

In setData you always set the value of mov[0]. The class member i will never change (loop variable hides it). You do not use the parameter m to set the data.
Change your setData to
m.setName(name);
m.setDirector(director);
m.setfileSize(fileSize);
m.setDuration(duration);

Related

Keep a Record of User Input - Java

I'm making a event scheduler in Java, and so far I can only add one event. However, I'd like to be able to add more than one event and be able to display them, but the only other option I can think of is using arrays.
I also have a counter called numOfCreatedEvents to keep track of the events and increments when an event is created.
Example of user input
Enter the event ID: A12
Enter the event title: Lorem Ipsum
Enter the fee: $ 10.0
Enter the maximum attendee limit: 15
Enter the start time: 14
Enter the duration time in minutes: 120
Enter requirements (optional): Wear shoes.
Below is my program attempting to use arrays, but when I call the setter methods, they have an error (marked in the code below).
Event.java
Scanner sc = new Scanner(System.in);
// Private instance variables.
private String[] ID;
private String[] title;
private double[] baseFee;
private int[] maxAttendeeLimit;
private int[] startTime;
private int[] durationTime;
private String[] requirements;
private int numOfCreatedEvents;
// Getters.
public String[] getID() {
return this.ID;
}
public String[] getTitle() {
return this.title;
}
public double[] getBaseFee() {
return this.baseFee;
}
public int[] getMaxAttendeeLimit() {
return this.maxAttendeeLimit;
}
public int[] getStartTime() {
return this.startTime;
}
public int[] getDurationTime() {
return this.durationTime;
}
public String[] getRequirements() {
return this.requirements;
}
// Setters.
public void setID(String[] ID) {
this.ID = ID;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setBaseFee(double[] baseFee) {
this.baseFee = baseFee;
}
public void setMaxAttendeeLimit(int[] maxAttendeeLimit) {
this.maxAttendeeLimit = maxAttendeeLimit;
}
public void setStartTime(int[] startTime) {
this.startTime = startTime;
}
public void setDurationTime(int[] durationTime) {
this.durationTime = durationTime;
}
public void setRequirements(String[] requirements) {
this.requirements = requirements;
}
// Schedule a event.
public void scheduleAEvent() {
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("---------------------");
System.out.print("Enter the event ID: ");
String eventID = sc.nextLine();
setID(eventID); // Error here.
System.out.print("Enter the event title: ");
String eventTitle = sc.nextLine();
setTitle(eventTitle); // Error here.
System.out.print("Enter the fee: $");
String baseFee = sc.nextLine();
double eventBaseFee = Double.parseDouble(baseFee);
setBaseFee(eventBaseFee); // Error here.
System.out.print("Enter the maximum attendee limit: ");
String maxAttendeeLimit = sc.nextLine();
int eventMaxAttendeeLimit = Integer.parseInt(maxAttendeeLimit);
setMaxAttendeeLimit(eventMaxAttendeeLimit); // Error here.
System.out.print("Enter the start time: ");
String startTime = sc.nextLine();
int eventStartTime = Integer.parseInt(startTime);
setStartTime(eventStartTime); // Error here.
System.out.print("Enter the duration time in minutes: ");
String durationTime = sc.nextLine();
int eventDurationTime = Integer.parseInt(durationTime);
setDurationTime(eventDurationTime); // Error here.
System.out.print("Enter requirements (optional): ");
String requirements = sc.nextLine();
setRequirements(requirements); // Error here.
// Increase the created event count.
numOfCreatedEvents++;
}
// Print event details.
public void printDetails() {
System.out.println("\n~ EVENTS ~");
System.out.println("-----------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
// Display the records of events scheduled.
for(int i = 0; i < numOfCreatedEvents; i++) {
System.out.format(pattern, getID(), getTitle(), "$" + getBaseFee(), getMaxAttendeeLimit(), getStartTime(), getDurationTime(), getRequirements());
}
}
Main.java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input;
Event event = new Event();
// Main menu.
do {
System.out.println("\n~ EVENT BOOKING SYSTEM ~");
System.out.println("------------------------");
System.out.println("A. Schedule an Event");
System.out.println("B. View Event Details");
System.out.println("X. Exit\n");
System.out.print("Select an option: ");
input = sc.nextLine();
input = input.toUpperCase();
switch(input) {
case "A":
event.scheduleAnEvent();
break;
case "B":
event.printDetails();
break;
case "X":
System.out.println("INFO: You have exited the booking system.");
break;
default:
System.out.println("ERROR: Invalid input!");
}
} while (input.equals("X") == false);
sc.close();
}
Problem: How do I add multiple events and keep a record of them when I call printDetails() to list all of them?
Thank you for your help!
The error is because your setter methods want to take in an array (denoted by the "[]" after the type in the method header), but the places you've marked as an error are attempting to send just a single piece of data of the given type. I think it would be best if you created an Object to represent an event, then had an array that stored these objects. Here's a quick mock-up:
In a file called CalendarEvent.java:
public class CalendarEvent {
private String ID;
private String title;
private double baseFee;
private int maxAttendeeLimit;
private int startTime;
private int durationTime;
private String requirements;
// Getters
public String getID() { return this.ID; }
public String getTitle() { return this.title; }
public double getBaseFee() { return this.baseFee; }
public int getMaxAttendeeLimit() { return this.maxAttendeeLimit; }
public int getStartTime() { return this.startTime; }
public int getDurationTime() { return this.durationTime; }
public String getRequirements() { return this.requirements; }
// Setters
public void setID(String ID) { this.ID = ID; }
public void setTitle(String title) { this.title = title; }
public void setBaseFee(double baseFee) { this.baseFee = baseFee; }
public void setMaxAttendeeLimit(int maxAttendeeLimit) { this.maxAttendeeLimit = maxAttendeeLimit; }
public void setStartTime(int startTime) { this.startTime = startTime; }
public void setDurationTime(int durationTime) { this.durationTime = durationTime; }
public void setRequirements(String requirements) { this.requirements = requirements; }
// this should return a String, built similarly to how you previously did it in your printDetails method
public String toString() {
return ID + " - " + title;
}
// other methods related to modifying a single event go here
// ...
}
In another class called EventHandler.java:
import java.util.Scanner;
public class EventHandler {
CalendarEvent[] myEvents;
public void scheduleAEvent() {
Scanner sc = new Scanner(System.in);
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("---------------------");
CalendarEvent toAdd = new CalendarEvent();
System.out.print("Enter the event ID: ");
toAdd.setID(sc.nextLine());
System.out.print("Enter the event title: ");
toAdd.setTitle(sc.nextLine());
System.out.print("Enter the fee: $");
toAdd.setBaseFee(sc.nextDouble());
System.out.print("Enter the maximum attendee limit: ");
toAdd.setMaxAttendeeLimit(sc.nextInt());
System.out.print("Enter the start time: ");
toAdd.setStartTime(sc.nextInt());
System.out.print("Enter the duration time in minutes: ");
toAdd.setDurationTime(sc.nextInt());
System.out.print("Enter requirements (optional): ");
toAdd.setRequirements(sc.nextLine());
}
// Print event details
public void printDetails() {
System.out.println("\n~ EVENTS ~");
System.out.println("-----------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
// Display the records of events scheduled.
for(int i = 0; i < myEvents.length; i++) {
System.out.println(myEvents[i]);
}
}
}
I would suggest doing some reading on object oriented design, this is a much more organized way to structure your data. Best of luck, hope this helps.
I am 100% clear what your expectation is. But the looks from your code, you are trying to set a String value to a method that is expecting an array of Strings. i.e. String[]
I suggest to remove the array implementation and replace with List<String>. For example:
private List<String> ID;
public void setID( String i )
{
if( ID == null )
{
ID= new ArrayList<>();
}
ID.add( i );
}
public List<String> getID()
{
return ID;
}
Do this for all the variables. That is ID, Title, baseFee, maxAttendeeLimit, startTime, durationTime, requirements. Because arrays are fixed types and you cannot increment the size of an existing array once created. Access the elements like ID.get(i) within the loop
Here's another example solution.
In the file below, I've removed all of the setters and replaced it with a constructor instead.
Reservation.java
public class Reservation {
private String ID;
private String title;
private double baseFee;
private int maxAttendeeLimit;
private int startTime;
private int durationTime;
private String requirements;
public Reservation(String ID, String title, double baseFee, int maxAttendeeLimit, int startTime, int durationTime, String requirements) {
this.ID = ID;
this.title = title;
this.baseFee = baseFee;
this.maxAttendeeLimit = maxAttendeeLimit;
this.startTime = startTime;
this.durationTime = durationTime;
this.requirements = requirements;
}
public String getID() {
return this.ID;
}
public String getTitle() {
return this.title;
}
public double getBaseFee() {
return this.baseFee;
}
public int getMaxAttendeeLimit() {
return this.maxAttendeeLimit;
}
public int getStartTime() {
return this.startTime;
}
public int getDurationTime() {
return this.durationTime;
}
public String getRequirements() {
return this.requirements;
}
}
Below I've also used an array to store the reservation information.
Main.java
private Reservation[] reservation = new Reservation[5];
private int reservationCounter;
public void printDetails() {
System.out.println("\n~ RESERVATIONS ~");
System.out.println("----------------");
String pattern = "%-25s %-50s %-25s %-43s %-34s %-34s %-1s\n";
System.out.printf(pattern, "ID", "Title", "Fee", "Maximum Attendee Limit", "Start Time", "Duration Time", "Requirements");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
for(int i = 0; i < reservationCounter; i++)
System.out.format(pattern, reservation[i].getID(), reservation[i].getTitle(), "$" + reservation[i].getBaseFee(), reservation[i].getMaxAttendeeLimit(), reservation[i].getStartTime(), reservation[i].getDurationTime(), reservation[i].getRequirements());
}
Hope this helps!

How to sort content of a csv file in java

I have a big csv file that looks like this
Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology
I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
int choice=0;
boolean flag = true;
while (flag) {
System.out.println("Enter 1 to display data.");
System.out.println("Enter 2 to sort data.");
System.out.println("Enter 3 to idk.");
System.out.println("Enter 0 to exit.");
System.out.print("Your choice: ");
choice = input.nextInt();
if (choice ==1) {
File inputFile = new File("dataToLoad.csv");
String line;
String delimiter = ",";
Scanner in = new Scanner(inputFile);
int numberOfLines = 0;
int numberOfColumns = 0;
while (in.hasNextLine()){
line = in.nextLine();
numberOfLines++;
}
in.close();
String[][] data = new String[numberOfLines][8];
in = new Scanner(inputFile);
int currentRow = 0;
while (in.hasNextLine()){
line = in.nextLine();
String[] parts = line.split(delimiter);
numberOfColumns = parts.length;
for (int i = 0; i<numberOfColumns; i++) {
data[currentRow][i] = parts[i];
}
currentRow++;
}
in.close();
System.out.println(Arrays.deepToString(data));
for (int row=0; row<numberOfLines; row++) {
for (int col=0; col<numberOfColumns; col++) {
System.out.printf("%-20s", data[row][col]);
}
System.out.println();
}
}
else {
if (choice ==2) {
}
else
if (choice==0) {
System.out.println("Good bye!");
flag = false;
}
else System.out.println("I am sorry, this is not a valid option. Please try again.");
}
}
}
}
As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.
Stop reinventing the wheel; use a csv open source library (for example, opencsv).
Create a class that represents one row of data in your csv file; I'll refer to this as RowClass.
Read the CSV file one row at a time. Each row will arrive as a String[].
Create and populate one instance of RowClass per row of the CSV file.
Store the RowClass objects in a List; I'll call this rowList.
Sort rowList using a Comparator that you create. Create one Comparator for each sort option.
Implement RowClass.toString() to display one row.
This should help, I believe that you will figure out what's going on here
Main.java
package pkg;
import java.util.Arrays;
import static pkg.Order.OrderBuilder;
public class Main {
private static Order[] orders = new Order[3];
private static OrderBuilder orderBuilder = new OrderBuilder();
public static void main(String[] args) {
Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();
orders[0] = order3;
orders[1] = order1;
orders[2] = order2;
System.out.println("Before sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
Arrays.sort(orders);
System.out.println("After sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
}
}
Order.java
package pkg;
public class Order implements Comparable<Order> {
private int id;
private String priority;
private float quantity;
private float price;
private String shipMode;
private String customerName;
private String customerSegment;
private String productCategory;
private void setId(int id) {
this.id = id;
}
int getId() {
return this.id;
}
private void setPriority(String priority) {
this.priority = priority;
}
private void setQuantity(float quantity) {
this.quantity = quantity;
}
private void setPrice(float price) {
this.price = price;
}
private void setShipMode(String shipMode) {
this.shipMode = shipMode;
}
private void setCustomerName(String customerName) {
this.customerName = customerName;
}
private void setCustomerSegment(String customerSegment) {
this.customerSegment = customerSegment;
}
private void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
#Override
public int compareTo(Order o) {
return this.id - o.getId();
}
static class OrderBuilder {
private Order order;
OrderBuilder withId(int id) {
order.setId(id);
return this;
}
OrderBuilder withPriority(String priority) {
order.setPriority(priority);
return this;
}
OrderBuilder withQuantity(float quantity) {
order.setQuantity(quantity);
return this;
}
OrderBuilder withPrice(float price) {
order.setPrice(price);
return this;
}
OrderBuilder withShipMode(String shipMode) {
order.setShipMode(shipMode);
return this;
}
OrderBuilder withCustomerName(String customerName) {
order.setCustomerName(customerName);
return this;
}
OrderBuilder withCustomerSegment(String customerSegment) {
order.setCustomerSegment(customerSegment);
return this;
}
OrderBuilder withProductCategory(String productCategory) {
order.setProductCategory(productCategory);
return this;
}
OrderBuilder createNewOrder() {
order = new Order();
return this;
}
Order build() {
return order;
}
}
}

convert a integer to array of class type java

I take in a file which has a name (table) and the number of seats:
table1 6
table2 2
table3 4
I have an array of class Reservation which will take in the the name and the seat. I am having trouble converting the number of seats into the array. How do i go about doing so?
public class Reservable {
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
id = fileIn.next();
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i] = seat;
}
}
}
here is my Reservation class:
public class Reservation {
private String name;
private int timeSlot;
private Reservable myReservable;
public Reservation(String name, int timeSlot) {
this.name = name;
this.timeSlot = timeSlot;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
public Reservable getMyReservable() {
return myReservable;
}
public void setMyReservable(Reservable myReservable) {
this.myReservable = myReservable;
}
public boolean isActive() {
return false;
}
You can read line by line since your file has a reservation by line.
I propose you to have a Reservation constructor with two parameters (name and nbSeat).
A remark : you array of reservation has a fixed size : 10. If you file has more than 10 elements, a ArrayIndexOutOfBoundsException will be risen.
If the number of reservation may be superior to 10 or is variable, you should use a List rather than a array.
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
int i=0;
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] token = line.split("\\s");
String name = token[0];
int nbSeat= Integer.valueOf(token[1)];
// add in your array
Reservation reservation = new Reservation(name,nbSeat);
arrayRes[i] = reservation ;
}
i++;
}
And Reservation :
public class Reservation{
public Reservation(String name, int nbSeat){
this.name=name;
this.nbSeat=nbSeat;
}
}
You need to show us what your Reservation class looks like, but if it uses the conventional getters and setters this is the correct way:
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i].setSeat(seat);
id = fileIn.next();
arrayRes[i].setId(id);
}
}
}

Java: How would I declare an undefined number of object with user inputted data?

for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!
import java.util.Scanner;
public class Item
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
private String name;
private double price;
public static final double TOLERANCE = 0.0000001;
public Item(String name,double price)
{
this.name = name;
this.price = price;
}
public Item()
{
this("",0.0);
}
public Item(Item other)
{
this.name = other.name;
this.price = other.price;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public void setName(String name)
{
this.name = name;
}
public void setPrice(double price)
{
this.price = price;
}
public void input(String n, double item)
{
}
public void show()
{
// Code to be written by student
}
public String toString()
{
return "Item: " + name + " Price: " + price;
}
public boolean equals(Object other)
{
if(other == null)
return false;
else if(getClass() != other.getClass())
return false;
else
{
Item otherItem = (Item)other;
return(name.equals(otherItem.name)
&& equivalent(price, otherItem.price));
}
}
private static boolean equivalent(double a, double b)
{
return ( Math.abs(a - b) <= TOLERANCE );
}
}
As I understood you want just initialize an array of obects.
Firstly you need initialize an array:
int n = scanner.nextInt(); // you may get n in other way
Item[] items = new items[n];
Then you can fill it with new instances of Item:
for(int i = 0; i < n; i++){
items[i] = new Item(); //constructor args may be here
}
To add undefined number of object best choice is List in java. By using your example i add some code in main() method as below :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Item> items = new ArrayList<>();
while (true) {
System.out.println("--------------------------------");
System.out.print("Enter item name :: ");
String name = input.next();
System.out.print("Enter item price :: ");
while (!input.hasNextDouble()) {
System.err.println("Invalid Price (Double) eg. 300");
System.out.print("Enter item price :: ");
input.next();
}
double price = input.nextDouble();
Item item = new Item(name, price); //creating object by passing value in constructor
items.add(item); //adding object in list
System.out.println("Do you want to add more items ? 'Y'=>Yes or 'N'=>No ");
String ans = input.next();
if ("N".equalsIgnoreCase(ans)) {
break;
}
}
//To retrive item object list
for (Item i : items) {
System.out.println(i);
}
}

Print out customer name, id, balance

I am writing a Java program that I need:
A method to read the customer names and id and store them in an array. (Read a sequence of zero or more lines each containing the name and id of one customer. Instantiate one Customer object per line and store each object in an array of objects. The array need not be more than 10 elements long. The sequence of name and id will end with an empty line).
Main
import java.util.Scanner;
public class CustomerTest {
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
int numItem;
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
int numItem = 0;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
} else {
input[numItem] = name; //error
input[numItem] = id; //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i <numItem && !found) { //error
if (customers[i].equals(id)) { //error
changeBalance(double value);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(customers[i].toString()); //error
}
}
}
Can you please check if this works.
I dont know whether I understood your question.And I just cleared the error.
public class CustomerTest {
static int numItem = 0;
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
}
else {
input[numItem].getName();
input[numItem].getId(); //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
Customer cust = new Customer();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i < numItem && !found) { //error
if (input[i].equals(id)) { //error
cust.changeBalance(amount);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(input[i].toString()); //error
}
}
}
Let me know your thoughts.
Customer.java
public class Customer {
private String name;
private String id;
private double balance;
public Customer(){
}
public Customer(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public void changeBalance(double value) {
balance = balance + value;
}
public String toString() {
return "name " + name + " id " + id + " balance " + balance;
}
}

Categories

Resources