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]
Related
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;
}
I'm trying to call addContact method from main method using ArrayList called phone but its not working.
Here's the code:
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
public void addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
}
}
public class Main {
static void menu() {
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone;
while(true) {
menu();
int c = sc.nextInt();
if(c==1) {
phone.add().addContact();
//I'm trying to call addContact()
} else if(c==2) {
break;
}
}
}
}
Why I can't just call phone.add().addContact()?
import java.util.ArrayList;
import java.util.Scanner;
class A {
String name;
int num;
Scanner sc = new Scanner(System.in);
public A(String name, int num) {
this.name= name;
this.num= num;
}
}
public class Main {
static void menu()
{
System.out.println("1. add");
System.out.println("2. break");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList <A> phone = new Arraylist<A>();
while(true)
{
menu();
int c = sc.nextInt();
if(c==1)
{
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter number:");
int num = sc.nextInt();
phone.add(new A(name,num));
}
else if(c==2)
{
break;
}
}
}
}
Just removed you addContact and placed in in the while. Now i create a new Instance of A and add it to the list. This should work now. Please post more precise Questions in the future.
You need to create an instance of your list:
ArrayList<A> phone = new ArrayList<>();
ArrayList <A> phone;
Should be:
ArrayList phone = new ArrayList();
Also, the add() method in this line
phone.add().addContact();
should contain an A object to add to the ArrayList.
you need to return object of A
public A addContact() {
sc.nextLine();
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter number:");
num = sc.nextInt();
return new A(name,num);
}
and
if(c==1)
{
phone.add(addContact);
}
Your problem starts here:
ArrayList <A> phone;
only declares that list; but doesnt define it. Thus you run into a NullPointerException when you try to run your code.
You need
ArrayList <A> contacts = new ArrayList<>();
instead. I took the freedom to give that variable a reasonable name, too. (this list is about storing contents, it is not storing phones; and it is also not a single phone ... just a list of contact information)
But there is more. You see, you are getting your abstractions wrong. Your Contact class (A is just a terrible name for that class) should not be dealing with a scanner to fetch its data.
Instead, you want to do something like:
class Contact {
private final String name;
private final int number;
Contact(String name, int number) {
this.name = name;
this.number = number;
}
and then, within your main method, you do something like:
boolean loop = true;
while (loop) {
... have user enter a name and a number
if (name.equals("STOP")) {
loop = false;
} else {
Contact contact = new Contact(name, number);
phones.add(contact);
}
}
I can't give the working code. Just check below points to make your program better.
Why you are creating constructor with arguments when you using add contact method.
Where you are created object for class A in class Main.
Try to check how to use ArrayList class. Because you are not using add() properly.
So I'm working on a (supposedly) simple java application that uses console inputs from a user, to change private variables in another class. Now I can change the value of the private variables in the EmpCls class directly from the main class by manually inputting a variable into the object, e.g.
EmpCls empObject1 = new EmpCls("josh"); but how do I get something like this
EmpCls empObject1 = new EmpCls(ctName); to work? where ctName is the variable that the user inputs. here's the relevant code from the main class:
import java.util.*;
public class NewWan {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
EmpCls empObject1 = new EmpCls(ctName);
String ctName = empObject1.getName();
System.out.println("enter name: ");
ctName = console.next();
}
}
And the subclass in question:
public class EmpCls {
private String name;
private String ext;
private int yearStarted = 0;
public EmpCls()
{
}
public EmpCls(String inName)
{
this.name = inName;
}
public void setEmpDetails(String inName) //, String inExt, int inYearStarted)
{
this.name = inName;
// this.ext = inExt;
// this.yearStarted = inYearStarted;
}
public String getName()
{
return this.name;
}
public int getYearStarted()
{
return this.yearStarted;
}
public String getExt()
{
return this.ext;
}
public void displayDetails()
{
System.out.println("Name: " + name);
System.out.println("Ext: " + ext);
System.out.println("Year Started" + yearStarted);
}
}
some parts of the code are commented just to enable easier trouble shooting, other parts are part of a different problem im working on.
You just need to reorder the statements a bit and remove the one that doesn't make sense:
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
}
Hum... just to organize your code in the good way ? You use variable before getting value, and before declare it... Strange way ^^
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
System.out.println("You just enter " + empObject1.getName());
}
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++;
}
}
}
I am designing an Address Book and in order to make my AddressBookApp class work (which includes my main method) I have had to create instance variables and make them static in order for each method in my class to be able to access my Name, Email, and Phone objects. I assume that there is a better way, but am struggling to know what that is. Should I create the objects in the main method? Are instance variables the right way to go? Do you guys have any ideas as to how I can improve my design? (If you have any other design suggestions not related to my question then let me know)
Here is the code for my AddressBookApp class:
import java.util.Scanner;
public class AddressBookApp {
//Instance Variables
private static Name name;
private static Email email;
private static Phone phone;
//Constructor
public AddressBookApp() {
name = new Name();
email = new Email();
phone = new Phone();
}
//Main method
public static void main(String[] args) {
new AddressBookApp();
System.out.println("Welcome to the Address Book Application\n");
Scanner sc = new Scanner(System.in);
int menuNumber;
do {
menu();
menuNumber = sc.nextInt();
System.out.println();
if (menuNumber < 1 || menuNumber > 4){
System.out.println("Please enter a valid menu number\n");
} else if (menuNumber == 1) {
printEntries();
} else if (menuNumber == 2) {
addEntry();
} else if (menuNumber == 3) {
removeEntry();
} else {
System.out.println("Thanks! Goodbye.");
sc.close();
return;
}
continue;
} while (menuNumber != 4);
sc.close();
}
/**
* Prints out Main Menu
*/
public static void menu() {
System.out.println("1 - List entries\n" +
"2 - Add entry\n" +
"3 - Remove entry\n" +
"4 - Exit\n");
System.out.print("Enter menu Number: ");
}
/**
* Prints all entries in the Address Book
*/
public static void printEntries() {
name.printNames();
System.out.println();
email.printEmails();
System.out.println();
phone.printPhoneNumbers();
System.out.println();
}
/**
* Adds an entry to the Address Book
*/
public static void addEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name.addName(sc.nextLine());
System.out.print("Enter Email Address: ");
email.addEmail(sc.nextLine());
System.out.print("Enter Phone Number: ");
phone.addPhone(sc.nextLine());
System.out.println("\nRecord Saved.\n");
}
/**
* Removes and entry from the Address Book
*/
public static void removeEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter the record number that you would like to remove: ");
int records = sc.nextInt();
name.removeNames(records - 1);
email.removeEmail(records - 1);
phone.removePhone(records - 1);
}
}
AddressBook and AddressBookApp should be two different classes. AddressBook should look like this:
public class AddressBook {
//Instance Variables
private Name name;
private Email email;
private Phone phone;
//Constructor
public AddressBook() {
name = new Name();
email = new Email();
phone = new Phone();
}
// more Constructors
public void setName(Name name) {
this.name = name
}
public Name getName() {
return name;
}
// more getters and setters
Your app can then create an instance of this in your main() method:
AddressBook book = new AddressBook();
book.setName(new Name("Jeff"));
//more operations on book
You can pass around the object book to any methods in which you need it or keep creating new instances. You can also have it as a static reference in your app class:
private static AddressBook book = new AddressBook();
// in your app class methods
book.burnBeforeReading();
Simple, create two classes: Main and AddressBook.
Main only has
public static void main(String[] args) {
new AddressBook().execute();
...
AddressBook only has instance methods.