How do I load data file into an arraylist - java

I need help creating a method that loads pets. I am having difficulty
writing a while loop that reads the file pets.txt and stores it in an array
list and returns the total number of pets. Once I have the pets loaded I
need to create a method to print the list, a method to find the heaviest
pet and a method to find the average weight of the pets.
Here is what I have so far:
try {
inFile = new Scanner(new FileReader("pets.txt"));
} catch (FileNotFoundException ex) {
System.out.println("File data.txt not found");
System.exit(1);
}
int i = 0;
while (inFile.hasNext() && i < list.length) {
// cant figure out how to write this
i++;
}
inFile.close();
return i;
pets.txt looks like this:
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
The format of this information is
(name of pet, name of owner, weight, breed)

Solution
This is my solution to this problem with the methods that you mentioned that you wanted. I simply just create a pet class and create an arraylist of the pet object and add the pet objects to the list when I use the scanner to get the data from the file!
Pet Class
public class Pet {
//Fields Variables
private String pet_name;
private String owner_name;
private double weight;
private String breed;
//Constructor
public Pet (String name, String o_name, double weight, String breed) {
//Set the variable values
this.pet_name = name;
this.owner_name = o_name;
this.weight = weight;
this.breed = breed;
}
//Getter and setter
public String getPet_name() {
return pet_name;
}
public void setPet_name(String pet_name) {
this.pet_name = pet_name;
}
public String getOwner_name() {
return owner_name;
}
public void setOwner_name(String owner_name) {
this.owner_name = owner_name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Main Class
public class Main {
//ArrayList
private static ArrayList<Pet> pets = new ArrayList<>();
public static void main (String [] args) {
try {
Scanner sc = new Scanner(new File("path/to/file.txt")).useDelimiter(", |\n");
while (sc.hasNext()) {
//Get the info for the pet
Pet pet;
String name = sc.next();
String owner_name = sc.next();
double weight = sc.nextDouble();
String breed = sc.next();
//Create the pet and add it to the array list
pet = new Pet (name, owner_name, weight, breed);
pets.add(pet);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Add your custom pets here if you would like!
addNewPet ("muffy", "john", 30.0, "beagle");
//Custom Methods
printList();
findHeaviestPet();
findLightestPet();
getAveragePetWeight();
}
public static void printList () {
for (int i = 0; i < pets.size(); i++) {
System.out.println (pets.get(i).getPet_name()+" "+pets.get(i).getOwner_name()
+" "+pets.get(i).getWeight()+" "+pets.get(i).getBreed());
}
}
public static void findLightestPet () {
//So we know the value will be assigned on the first pet
double weight = Double.MAX_VALUE;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() < weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The lightest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void findHeaviestPet () {
double weight = 0.0;
int petIndex = 0;
for (int i = 0; i < pets.size(); i++) {
if (pets.get(i).getWeight() > weight) {
weight = pets.get(i).getWeight();
petIndex = i;
}
}
System.out.println("The heaviest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight());
}
public static void getAveragePetWeight() {
double weights = 0;
for (int i = 0; i < pets.size(); i++) {
weights += pets.get(i).getWeight();
}
weights = (weights / pets.size());
System.out.println ("The average weight is "+weights);
}
public static void addNewPet (String name, String o_name, double weight, String breed) {
Pet pet = new Pet(name, o_name, weight, breed);
pets.add(pet);
}
}
Pets.txt
Please make sure that between every item there is a command and space like this ", " that is so we know when the next item is.
muffin, bobby, 25.0, pug
tiny, seth, 22.0, poodle
rex, david, 40.0, lab
lucy, scott, 30.0, bulldog
name, owner_name, 65.0, breed

In your loop you iterate over every line of the file. So you have to parse the line in it´s content (Split) and then save the informations in
Second you should create an Pet-Object (Objects and Classes) and save the information in each object. Your arraylist contains the created objects.
If you got some specific code, maybe someone will give you a more specific help.

What you have done so far is too "load" the file. You must now use the inFile (the scanner object) to access the contents of the pets.txt. This can be done in many ways such as using inFile.nextLine() (see the Javadocs).
Thereafter use string methods such as split() (again see the docs) to extract whichever parts of the string you want in the necessary format, to store in a Pets class.
You should then store each Pets object in a data structure (e.g. list) to enable you to write the methods you need in an efficient manner.

Pet Class
Public class Pet {
Public Pet(String pet_name, String owner, float weight, String breed) {
this.pet_name = pet_name;
this.owner = owner;
this.weight = weight;
this.breed = breed;
}
String pet_name;
String owner;
float weight;
String breed;
//implements getters and setters here
}
File reading method
private void read_file() throws Exception {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
List<Pet> list = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
Pet pet = new Pet(data[0], data[1], Float.valueOf(data[2]), data[3]);
list.add(pet);
}
}

First of all I would not read the data into a simple array list. I would probably use an ArrayList of classes. So I would declare a second class something like this:
//Declare pet class
class Pet{
// Can be either public or private depending on your needs.
public String petName;
public String ownerName;
public double weight;
public String breed;
//Construct new pet object
Pet(String name, String owner, double theWeight, String theBreed){
petName = name;
ownerName = owner;
weight = theWeight;
breed = theBreed;
}
}
Then back in whatever your main class is I would make the following method:
public ArrayList<Pet> loadFile(String filePath){
ArrayList<Pet> pets = new ArrayList<Pet>();
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String s[] = sc.nextLine().split(",");
// Construct pet object making sure to convert weight to double.
Pet p = new Pet(s[0],s[1],Double.parseDouble(s[2]),s[3]);
pets.add(p);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return pets;
}

Related

How to deal with null in an array when iterating

I am dealing with a classical Nim game project. The hurdle for me is to "only" use an array to save player in an object array, which means I will always get NullPointerException when testing. And I've searched almost all the information that there is no such a way to handle this problem.
One way to deal with it is to add if arr[i] != null for checking non-null object when iterating, but then, I need to write it for every method I created. Is there any way to pass only the non-null array to be checked?
Here is part of my code Nimsys:
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
addPlayer(name);
}
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n) \n");
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
NimPlayer.getPlayer()[i] = null;
}
System.out.println("Remove all the players");
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
}
}
public static void searchAndRemovePlayer(String user) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!\n");// A test to see if the code runs
return;
}
}
System.out.println("The player does not exist.\n");
}
}
And, below is part of my NimPlayer class.
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 5;
static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter<SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
//getters and setters
}
You can do as below,
public static void searchAndRemovePlayer(String user) {
NimPlayer[] players = Arrays.stream(NimPlayer.getPlayer())
.filter(Objects::nonNull)
.toArray(NimPlayer[]::new);
for (int i = 0; i < players.length; i++) { // replaced NimPlayer.getCounter() to avoid Index Out of Bound
String userName = players[i].getUserName().trim();
if (userName.equals(user)) {
players[i] = null;
System.out.println("Remove successfully!\n");// A test to see if the code runs
return;
}
}
System.out.println("The player does not exist.\n");
}
Note that NimPlayer.getCounter() is replaced with arr length to avoid ArrayIndexOutOfBoundsException
Update:
You can add the logic in getPlayer()
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList)
.filter(Objects::nonNull)
.toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers;
}
Try to create a non-null array outside the given section of the program. In the sense, use a loop to create a non-null array that you can use throughout both programs and you can probably store that in a method or instance variable.

Creating a method and returning object

I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.

method header for user-defined array

public class studentDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many students are there?: ");
int numberOfstuds = scan.nextInt();
int[] nOEarray = new int[numberOfstuds];
System.out.println("\nEnter names of students up to the entered amount (" + numberOfstuds + "):");
String[] namesArray = new String[numberOfstuds];
for (int i = 0; i < numberOfstuds; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
That is part of my code for letting user input array size, however I am tasked with using the header below just for a method to get the size of the array, but I have tried inserting it and keep getting different error messages such as needs body(if I put semi-colon) or "requires ';'" if I don't and when I put curly braces around the section where it gets the array size it returns errors :Syntax error, insert "[ ]" to complete Dimension
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on token "create", AnnotationName expected after
this token
public static Student[] create()
Here is the Student class
public class Student {
//private data members
private String name;
private long idNUmber;
//constructor
public Student(){
name="Unassigned";
idNUmber=0;
}
//overloaded constructor
public Student(String x, long y) {
name=x;
idNUmber=y;
}
//getters
public String getName() {
return name;
}
public long getIdNUmber() {
return idNUmber;
}
//setters
public void setName(String n) {
name=n;
}
public void setIdNUmber(long i) {
idNUmber=i;
}
//override
public String toString() {
return "Name: "+getName()+"\nID number: "+getIdNUmber();
}

method to add objects to ArrayList using user input

Can't take my head around the following: There are 2 classes - "Item", where attributes (Name, Price) and constructors are set, and main "Store". In the last one - Arraylist, which fills up with Items depending on user input. The code works.
Here is the question: Is there any way to put all from the main class, apart from "ArrayList listOfItems=new ArrayList();" line into a method "addItem()" and then just call the method? I do not know how to do it. Tried a lot.
Thank you
package store;
import java.util.ArrayList;
import java.util.Scanner;
public class Store extends Item {
public static void main(String[] args) {
ArrayList<Item> listOfItems=new ArrayList<Item>();
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
listOfItems.add(new Item(name,price));
}
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
}
This will work for you:
package store;
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
private static class Item {
private String name;
private double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public static void main(String[] args) {
ArrayList<Item> listOfItems = new ArrayList<Item>();
addItem(listOfItems);
}
private static void addItem(ArrayList<Item> listOfItems) {
for (int i = 0; i < 2; i++) {
System.out.println("ENTER NAME");
Scanner addName = new Scanner(System.in);
String name = (addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice = new Scanner(System.in);
double price = (addPrice.nextDouble());
listOfItems.add(new Item(name, price));
}
for (Item list : listOfItems) {
System.out.println("NAME " + list.getName() + ", PRICE " + list.getPrice());
}
}
}
I defined the class Item separately to make it compiling. Also I removed the extends Item from the store, because it is not needed.
I don't know exactly if this is what you are looking for, but you may try the following solution:
public class Store extends Item {
public static void main(String[] args) {
ArrayList<Item> listOfItems=new ArrayList<Item>();
addItem(listOfItems);
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
private static void addItem(ArrayList<Item> li) {
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
li.add(new Item(name,price));
}
}
}
You maybe also try to declare the ArrayList outside the main:
public class Store extends Item {
private static ArrayList<Item> listOfItems;
public static void main(String[] args) {
listOfItems=new ArrayList<Item>();
addItem();
for(Item list:listOfItems){
System.out.println("NAME "+list.getName()+", PRICE "+list.getPrice());
}
}
private static void addItem() {
for(int i=0;i<2;i++){
System.out.println("ENTER NAME");
Scanner addName=new Scanner (System.in);
String name=(addName.nextLine());
System.out.println("ENTER PRICE");
Scanner addPrice=new Scanner (System.in);
double price=(addPrice.nextDouble());
listOfItems.add(new Item(name,price));
}
}
}
Let me know if you need further help! :)
You could use a better Oriented Object approach to solve your problem.
Store extends Items this has not sense. The store contains items, so you only need a variable like your listOfItems for save all the items of the store.
Your public class Store is a good candidate to use the Singleton Pattern.
About the construction of your listOfItems: When a List is enough, then simply you should use just a List. Also, java 7 provide the type inference for generic instance creation.
From The Java SE Documentation: You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
So, you should use List<Item> listOfItems = new ArrayList<>() instead of ArrayList<Item> listOfItems = new ArrayList<Item>()
Each time that you use a Scanner you should close it.
The Singleton:
public class Store {
private static final Store INSTANCE = new Store();
private List<Item> listOfItems = new ArrayList<>();
private Store() {
// Private Constructor
// will prevent the instantiation of this class directly
}
public static Store getInstance() {
return INSTANCE;
}
public void addItems(List<Item> newlistOfItems) {
listOfItems.addAll(newlistOfItems);
}
public String printListOfItems() {
StringBuilder sb = new StringBuilder();
for (Item item : listOfItems) {
sb.append(" [NAME : " + item.getName() + ", PRICE : " + item.getPrice() + "]");
}
return sb.toString();
}
}
The POJO Item class
public class Item {
private String name;
private double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
The service interface for the management of items :
public interface ItemManagerService {
List<Item> createListOfItems();
}
The implementation:
public class ItemManagerServiceImpl implements ItemManagerService {
#Override
public List<Item> createListOfItems() {
List<Item> newListOfItems = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
try {
do {
System.out.println("ENTER NAME");
String name = scanner.nextLine();
System.out.println("ENTER PRICE");
while (!scanner.hasNextDouble()) {
System.out.print("You must enter a valid number! Try again: ");
scanner.next();
}
double price = scanner.nextDouble();
Item item = new Item(name, price);
newListOfItems.add(item);
System.out.println("Continue?[Y/N]");
scanner.nextLine();
} while (scanner.nextLine().equalsIgnoreCase("y"));
} finally {
scanner.close();
}
return newListOfItems;
}
}
A simple test :
public class MainApp {
public static void main(String[] args) {
ItemManagerService itemManagerService = new ItemManagerServiceImpl();
List<Item> newlistOfItems = itemManagerService.createListOfItems();
Store.getInstance().addItems(newlistOfItems);
System.out.println(Store.getInstance().printListOfItems());
}
}
The console output:
ENTER NAME
table
ENTER PRICE
12
Continue?[Y/N]
y
ENTER NAME
car
ENTER PRICE
50,8
Continue?[Y/N]
n
[NAME : table, PRICE : 12.0] [NAME : car, PRICE : 50.8]

Creating multiple objects with different names in a loop to store in an array list

I am trying to create mutliple objects of a type of class I made. I then want to transfer these values into the array list. How can I create objects using a while loop that have different names. For example here is my code now, but it would only make an object of one name.
Customer cust = new Customer("bob", 20.0);
and my constructor if you want to see:
public Customer(String customerName, double amount)
{
String name=customerName;
double sale=amount;
}
StoreTest class (with main method):
import java.util.ArrayList;
import java.util.Scanner;
public class StoreTest {
ArrayList<Customer> store = new ArrayList<Customer>();
public static void main (String[] args)
{
double sale=1.0; //so the loop goes the first time
//switch to dowhile
Scanner input = new Scanner(System.in);
System.out.println("If at anytime you wish to exit" +
", please press 0 when asked to give " +
"sale amount.");
while(sale!=0)
{
System.out.println("Please enter the " +
"customer's name.");
String theirName = input.nextLine();
System.out.println("Please enter the " +
"the amount of the sale.");
double theirSale = input.nextDouble();
store.addSale(theirName, theirSale);
}
store.nameOfBestCustomer();
}
}
Customer class:
public class Customer {
private String name;
private double sale;
public Customer()
{
}
public Customer(String customerName, double amount)
{
name=customerName;
sale=amount;
}
}
Store class (has methods for messing with arraylist:
import java.util.ArrayList;
public class Store {
//creates Customer object and adds it to the array list
public void addSale(String customerName, double amount)
{
this.add(new Customer(customerName, amount));
}
//displays name of the customer with the highest sale
public String nameOfBestCustomer()
{
for(int i=0; i<this.size(); i++)
{
}
}
}
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer class has variables called name and sale, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
You can use this code...
public class Main {
public static void main(String args[]) {
String[] names = {"First", "Second", "Third"};//You Can Add More Names
double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
List<Customer> customers = new ArrayList<Customer>();
int i = 0;
while (i < names.length) {
customers.add(new Customer(names[i], amount[i]));
i++;
}
}
}

Categories

Resources