Java Inventory - How to read a file using FileInputStream? - java

For one of my last assignments this semester, I had to create an inventory program that contained an array of Item objects. Each Item contains an ID (that is assigned when you add an item and CANNOT be modified), name, description, number of items on hand, and the unit price.
I also need to save and load files using File I/O Stream. I am able to save to a text file just fine. However, I am having trouble getting started on my readFile method. I was really trying to get through this assignment without asking for any help, but I am stumped. How would I read in text files using FileInputStream?
Item Class
import java.text.NumberFormat;
public class Item
{
private int ID;
private String name;
private String Desc;
private int onHand;
private double unitPrice;
public Item(int pID)
{
ID = pID;
}
public Item(int pID, String pName, String pDesc, int pOnHand, Double pUnitPrice)
{
ID = pID;
name = pName;
Desc = pDesc;
onHand = pOnHand;
unitPrice = pUnitPrice;
}
public void display()
{
NumberFormat dollars = NumberFormat.getCurrencyInstance();
System.out.printf("%-6s%-20s%-24s%-12s%-6s\n", ID, name, Desc, onHand, dollars.format(unitPrice));
}
// GETTERS AND SETTERS
public int getID()
{
return ID;
}
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
public void setDesc(String pDesc)
{
Desc = pDesc;
}
public String getDesc()
{
return Desc;
}
public void setOnHand(int pOnHand)
{
onHand = pOnHand;
}
public int getOnHand()
{
return onHand;
}
public void setUnitPrice(double pUnitPrice)
{
unitPrice = pUnitPrice;
}
public double getUnitPrice()
{
return unitPrice;
}
}
Inventory Class
import java.util.Scanner;
import java.io.PrintWriter;
import java.io. FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Inventory
{
int max = 30;
int count = 0;
Item myItem[] = new Item[max];
Scanner scannerObject = new Scanner(System.in);
public void addItem()
{
try{
if (count >= max)
{
System.out.println("\nNo more room!");
}else{
System.out.print("\nPlease enter name of item: ");
String lname = scannerObject.nextLine();
System.out.print("\nPlease enter a brief description of the item: ");
String ldesc = scannerObject.nextLine();
System.out.print("\nPlease enter the amount on hand: ");
int lonHand = scannerObject.nextInt();
System.out.print("\nPlease enter unit price of the item: $");
Double lunitPrice = scannerObject.nextDouble();
myItem[count] = new Item(count + 1, lname, ldesc, lonHand, lunitPrice);
count++;
System.out.println("\nThank you. The ID number for " + lname + " is " + count);
scannerObject.nextLine();
}
}catch(Exception e)
{
System.out.println("\nERROR! Please try again:\n");
scannerObject.nextLine();
}
}
public int findItem()
{
int found = -1;
int inputID =0;
try{
System.out.print("\nGreetings, please enter the ID number for item:\n");
inputID = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myItem[i].getID() == inputID){
found = i;
scannerObject.nextLine();
}
}
}catch(Exception e)
{
System.out.println("\nERROR!");
scannerObject.nextLine();
}
return found;
}
public void modify()
{
int lfound = findItem();
if (lfound == -1){
System.out.println("\nInvalid input! Please try again:");
scannerObject.nextLine();
}else{
try{
System.out.print("\nPlease enter name of item: ");
String lname = scannerObject.nextLine();
myItem[lfound].setName(lname);
System.out.print("\nPlease enter a brief description of the item: ");
String ldesc = scannerObject.nextLine();
myItem[lfound].setDesc(ldesc);
System.out.print("\nPlease enter the amount on hand: ");
int lonHand = scannerObject.nextInt();
myItem[lfound].setOnHand(lonHand);
System.out.print("\nPlease enter unit price of the item: $");
double lunitPrice = scannerObject.nextDouble();
myItem[lfound].setUnitPrice(lunitPrice);
scannerObject.nextLine();
}catch (Exception e)
{
System.out.println("\nInvalid command! Please try again: ");
scannerObject.nextLine();
}
}
}
public void displayAll()
{ System.out.println("_______________________________________________________________________________\n");
System.out.println(" Inventory ");
System.out.println("_______________________________________________________________________________\n");
System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
System.out.println("_______________________________________________________________________________\n");
for(int i = 0; i < count; i++){
myItem[i].display();
}
}
public void displayOne()
{
int lfound = findItem();
if (lfound == -1){
System.out.println("\nInvalid input! Please try again:");
}else{
System.out.println("_______________________________________________________________________________\n");
System.out.println(" Inventory ");
System.out.println("_______________________________________________________________________________\n");
System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
System.out.println("_______________________________________________________________________________\n");
myItem[lfound].display();
}
}
public void saveFile()
{
PrintWriter outputStream = null;
try{
outputStream =
new PrintWriter(new FileOutputStream("H:\\Java\\saveFile.txt"));
}catch (FileNotFoundException e)
{
System.out.println("Error!");
}
if(outputStream != null)
for(int i = 0; i < count; i++){
outputStream.println(myItem[i].getID());
outputStream.println(myItem[i].getOnHand());
outputStream.println(myItem[i].getUnitPrice());
outputStream.println(myItem[i].getName());
outputStream.println(myItem[i].getDesc());
}
outputStream.close();
}
}
User Class
import java.util.Scanner;
public class inventUser
{
public static void main(String[] args)
{
Inventory myInvent = new Inventory();
Scanner scannerObject = new Scanner(System.in);
int Choice = 0;
do{
dispMenu();
Choice = getChoice(scannerObject);
proChoice(Choice, myInvent);
}while (Choice !=0);
}
public static void dispMenu()
{
System.out.println("\n|=============================================|");
System.out.println("| |");
System.out.println("|******************Welcome********************|");
System.out.println("|_____________________________________________|");
System.out.println("| |");
System.out.println("| Press [1] To Add An Item |");
System.out.println("| |");
System.out.println("| Press [2] To Display One Item |");
System.out.println("| |");
System.out.println("| Press [3] To Display All Items |");
System.out.println("| |");
System.out.println("| Press [4] To Modify An Item |");
System.out.println("| |");
System.out.println("| Press [0] To Exit |");
System.out.println("|_____________________________________________|");
System.out.println("|=============================================|");
System.out.println("| Please Make Selection Now... |");
System.out.println("|=============================================|");
System.out.println("|_____________________________________________|\n");
}
public static int getChoice(Scanner scannerObject)
{
boolean x = false;
int pChoice = 0;
do{
try{
pChoice = scannerObject.nextInt();
x = true;
}catch (Exception e){
scannerObject.next();
System.out.println("\nInvalid command! Please try again:\n");
}
}while (x == false);
return pChoice;
}
public static void proChoice(int Choice, Inventory myInvent)
{
switch(Choice){
case 1: myInvent.addItem();
break;
case 2: myInvent.displayOne();
break;
case 3: myInvent.displayAll();
break;
case 4: myInvent.modify();
break;
case 0: System.out.println("\nHave a nice day!");
break;
}myInvent.saveFile();
}
}
Per my instructor, I need to have my save and read file methods in my inventory class. I need to invoke them in my user class. While I have a "getter" for my Item ID variable, I am not allowed to use a "setter".
I am still fairly new to Java, so please excuse any rookie mistakes. Again, any help is greatly appreciated! I looked in my book and Googled for examples but I could not find anything relevant to my situation.

To read a file using FileInputStream simply use:
Scanner input = new Scanner(new FileInputStream("path_to_file"));
Use methods of Scanner to read
while(input.hasNextLine()) { //or hasNextInt() or whatever you need to extract
input.nextLine() //... read in a line of text from the file
}
You can also use the File class if you wish to perform any File manipulations using File class methods
File myTextFile = new File("path_to_file");
Scanner input = new Scanner(new FileInputStream(myTextFile));
You need to of course catch the FileNotFoundException
Otherwise, it's really the same as you've been doing for PrintWriter.
Just switch FileOutputStream for FileInputStream, and PrintWriterfor Scanner, but do not forget to first close the file when switching from writing or reading from the file:
input.close() // or output.close()

Related

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

arrayList with 2+ objects stored, how to get a return if user searches for them

so with the program, the user inputs data for the object in one file Inv.java and then that information is stored in Product.java and in store.java. from store.java there is an arrayList which holds the information but when 2 items are attempted to be put in, the second object writes over the first, how can I fix this and how can I be able to call the objects back in Inv.java
code for Inv.java
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
public class Inv
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
String str;
char c;
int n=0;
System.out.println(" INVENTORY MANAGEMENT SYSTEM");
System.out.println("===============================================");
System.out.println("1. ADD PRODUCT DATA");
System.out.println("2. VIEW PRODUCT DATA");
System.out.println("3. VIEW REPRLENISHMENT STRATEGY");
System.out.println("===============================================");
System.out.println("4. EXIT PROGRAM");
while(n!=4)// Exits the program when 4 is pressed
{
System.out.print("\n Please enter option 1-4 to continue...: ");
n = Integer.parseInt(System.console().readLine());
// Reads user input and takes them to selected code.
if (n>4||n<1)
{
System.out.print("Invalid input, please try again...");
continue;
}
if (n==1)// Takes to option 1 or addItem()
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.addItem();
System.out.print("Would you like to enter another product ? (Y or N) : ");
str = console.next();
}
continue;
}
if (n==2)// Takes to option 2 or prodData
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.prodData();
System.out.println("\n***************************************************\n");
System.out.print("Stay viewing this page? (Y or N) ");
str = console.next();
}
continue;
}
else
if (n==3)// Takes to option 3 or replenStrat
{
System.out.print("View Replenishment Strategy.");
continue;
}
}
System.out.print("\nThank you for using this inventory management software.\n");
System.out.print("Developed by Xavier Edwards");
System.out.println("\n***************************************************\n");
}
// Global variables so that any class can call it and use the information in it
public static Product product;
public static Store store;
// Where the user inputs the data for the item
public static void addItem ()
{
Scanner console = new Scanner(System.in);
product = new Product();// initiates the product and store to being empty.
store = new Store();
String desc, id, str="";
double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
int stock = 0, demand = 0;
System.out.print("Please enter product description between 3 to 10 characters...: ");
desc = console.next();
desc = desc.toLowerCase();
product.setName(desc);
if ((desc.length() < 3 || desc.length() > 10))
{
System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
System.out.println("Try again with different input. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter price in $ : ");
price = console.nextDouble();
product.setPrice(price);
if (price < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter set up price. $ : ");
sUpPrice = console.nextDouble();
product.setsUpPrice(sUpPrice);
if (sUpPrice < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter unit- cost. $ : ");
unitCost = console.nextDouble();
product.setunitCost(unitCost);
if (unitCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the inventory cost. $ : ");
inventoryCost = console.nextDouble();
product.setinvCost(inventoryCost);
if (inventoryCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the amount in stock : ");
stock = console.nextInt();
product.setstock(stock);
if (stock < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the demand of the product : ");
demand = console.nextInt();
product.setdRate(demand);
if (demand < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.println("\n*****************************************\n");
System.out.print(desc +" Product was added successfully ");
System.out.println("\n*****************************************\n");
// stores the item in the array
store.add(product);
}
// Where the product information is being returned to the user
public static void prodData()
{
Scanner console = new Scanner(System.in);
String pOption, str;
System.out.print("\nEnter product description to view the data...\n");
pOption = console.next();//
product = store.getProduct(pOption); //Checks to see if the item is created
// so that data can be displayed
if (product != null){
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}else{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
}
}
code for Product.java
public class Product
{
public String name;
public double price, sUpPrice, unitCost, invCost;
public int stock, demand;
public Product()
{
name = "";
price = 0;
sUpPrice = 0;
unitCost = 0;
invCost = 0;
stock = 0;
demand = 0;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setsUpPrice(double sUpPrice) {
this.sUpPrice = sUpPrice;
}
public double getsUpPrice() {
return this.sUpPrice;
}
public void setunitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getunitCost() {
return this.unitCost;
}
public void setinvCost(double invCost) {
this.invCost = invCost;
}
public double getinvCost() {
return this.invCost;
}
public void setstock(int stock) {
this.stock = stock;
}
public int getstock() {
return this.stock;
}
public void setdRate(int demand) {
this.demand = demand;
}
public int getdRate() {
return this.demand;
}
}
code for store.java
import java.util.*;
import java.util.ArrayList;
public class Store{
public ArrayList <Product> ProductList = new ArrayList<Product> ();
public Store()
{
//ArrayList = "";
}
public void add(Product product)
{
ProductList.add(product);
}
public Product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
}
any help be with appreciated.
Problem is in Inv.addItem() method where you are instantiating variable store every time you invoke it.
store = new Store();
Looking at your code, you should instantiate it in Inv:
public static Store store = new Store();

How to remove objects from ArrayLists

So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}

JAVA So i have this code that i am using arrays of [60] and when i use the add command it rewrites all the previous statements i made

Could you please help me figure out why when i add a new book it overwrites all of the books with the current one? ---------------------- |Name| -|ISBN|-|Author|
for example i add a book called |game| | of | Thrones|
and if i go & add a book named |Song| | of | Ice and fire |
no matter if there are 10 books there they will all be renamed according to the last entry
(here Song of ice and fire)
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t" +
"1:Add a new Book\n\t" +
"2:Edit Book Infos\n\t" +
"3:Search a Book (with ISBN)\n\t" +
"4:Show all the Books\n\t" +
"5:Delete a Book (with ISBN)\n\t" +
"6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
} else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
} else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner(System.in);
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.util.Scanner;
public class Management {
Scanner input = new Scanner( System.in );
private Book[] books =new Book [60];
private String isbns = new Book().isbn;
private String name = new Book().name;
int current = 0;
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 3
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
}
return searchBook;
}
}
The problem is that vivlio always means the same book. You only create one Book object, here:
Book vivlio = new Book();
and proceed to add it to the list several times, while changing its name each time. However, since it's just one book that happens to be on the list several times, when you change one you change all.
You can make it better by simply changing the scope. Move the creation of the book inside the loop:
while(true) {
Book vivlio = new Book();
...
Now vivlio is initialized to a different book each time, instead of using the same book all the time.
Your problem: You create Book vivlio = new Book(); once and re-use it every time. So whenever you set a parameter, you set it for this one book and therefore overwrite what you did before.
The easiest solution is to move
Book vivlio = new Book();
into your while loop.
That will create a new Book object each time you run through the loop.
By the way, there would be some ways to improve the code. For example, don't reference another object's attribute directly, but use getter and setter methods. Also, it is pretty standard to start function names with lower case chars.
Book object is created only once and after calling the following method.
public void AddBook(Book vivlio) {
books[current] = vivlio;
current++;
}
You are just assigning the same object object to array.
That means you are changing the values inside vivlio again and again but referencing the same object in array to different places thats why you are getting the same output in all the books.
Here is the right code for your reference.
public class library {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
System.out
.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
Book vivlio = new Book();
System.out
.println("------------------MENU-------------------------------");
System.out
.print("\nENTER UR CHOICE\n\t1:Add a new Book\n \t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = "
+ title);
} else {
// ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
}
Hope this might solve your problem.

How to write contents of an array list to a text file?

I have this basic enough Java program that asks the user to input songs to a music library array list. From there the user can shuffle their songs, delete a song, delete all etc. It's nearly finished, I just have one issue I can't resolve. It happens when I try export the array list to a text file. Instead of the content of the array list, my output would look like this, as opposed to the details the user submitted:
"1: MainClass.SongClass#c137bc9
MainClass.SongClass#c137bc9"
I'll post my code below, I'd really appreciate if someone could point me in the right direction!
My Final Project class which serves as my main class:
package MainClass;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalProject extends UserInput {
public String nextInt;
public static void main(String[] args) {
// SongLibrary iTunes; //Object stores the file cars.txt
// iTunes = new SongLibrary("MUSIC LIBRARY.txt");
// songData CLO = iTunes.readFileIntoList();
UserInput ui;
ui = new UserInput();
Scanner input = new Scanner(System.in);
int opt;
//Calls Methods Class so methods can be used below
Menu menuFunctions = new Menu();
//Calls FileReaderTest Class so file can be read
SongLibrary Reader = new SongLibrary();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library!");
do {
//Menu Prompts printed to the screen for the user to select from
System.out.println(" ");
System.out.println("Main Menu:");
System.out.println("........ \n");
System.out.println("Press 0 to Exit");
System.out.println("Press 1 to Add a Song");
System.out.println("Press 2 to View All Songs");
System.out.println("Press 3 to Remove a Song");
System.out.println("Press 4 to Shuffle Library");
System.out.println("Press 5 to Play a Random song");
System.out.println("Press 6 to Remove ALL Songs");
System.out.println("Press 7 to Save Library\n");
//Monitors the next Int the user types
opt = input.nextInt();
//"if" statements
if (opt == 0) {
//This corresponds to the condition of the while loop,
//The program will exit and print "Goodbye!" for the user.
System.out.println(" ");
System.out.println("Goodbye!");
} else if (opt == 1) {
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
System.out.println(" ");
menuFunctions.addEntry();
} else if (opt == 2) {
//This method prints the contents of the Array List to the screen
System.out.println("\n");
menuFunctions.viewAll();
} else if (opt == 3) {
//This method allows the user to remove an indiviual song from
//their music library
System.out.println("\n");
menuFunctions.removeOne();
} else if (opt == 4) {
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
System.out.println("\n");
menuFunctions.shuffleSongs();
} else if (opt == 5) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.randomSong();
} else if (opt == 6) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.clearLibrary();
}
else if (opt == 7) {
try {
menuFunctions.saveLibrary();
} catch (FileNotFoundException x) {
System.out.println("File not found. " + x);
}
}
else {
//If the user selects an incorrect number, the console will
//tell the user to try again and the main menu will print again
System.out.println("\n");
System.out.println("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
My SongClass class which holds the constructor and Get/Set methods
package MainClass;
public class SongClass {
private int songMinutes;
private int songSeconds;
private String songTitle;
private String songArtist;
private String songAlbum;
private int songYear;
public SongClass(int m, int ss, String t, String art, String al, int y){
songMinutes = m;
songSeconds = ss;
songTitle = t;
songArtist = art;
songAlbum = al;
songYear = y;
}
//GET METHODS
public int getMinutes() {
return songMinutes;
}
public int getSeconds() {
return songMinutes;
}
public String getTitle() { //
return songTitle;
}
public String getArtist() {
return songArtist;
}
public String getAlbum() {
return songAlbum;
}
public int getYear() {
return songYear;
}
//SET METHODS
public void setMinutes(int m){
songMinutes = m;
}
public void setDuration(int ss){
songSeconds = ss;
}
public void setTitle(String t){
songTitle = t;
}
public void setArtist(String art){
songArtist = art;
}
public void setAlbum(String al){
songAlbum = al;
}
public void printSong(){
System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
}
}
My menu class which holds most of the methods used in the program
package MainClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class Menu {
public void add(SongClass s) throws NumberFormatException {
try {
songLibrary.add(s);
} catch (NumberFormatException x) {
}
}
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
public ArrayList<SongClass> songLibrary;
public Menu() {
songLibrary = new ArrayList<SongClass>();
}
public void removeOne() throws ArrayIndexOutOfBoundsException {
try {
System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
viewAll();
//calls the viewAll method to print current library to screen
int remove = input.nextInt();
//creates an int that corresponds to the nextInt typed.
if (remove > songLibrary.size()) {
System.out.println("Invalid ");
//if the user types a number higher than the highest index of the
//array list, they will be shown an error and return to the menu
}
else {
remove --;
SongClass s = songLibrary.get(remove);
System.out.println("Are you sure you would like to delete the following track from your music library? ");
s.printSong();
//confirms user wants to delete the selected track
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//Asks the user to input 1 or 2,
if (confirmDelete == 1) {
songLibrary.remove(remove);
//removes the index of the 4 array lists
System.out.println( "Removed.");
viewAll();
} else if (confirmDelete == 2) {
System.out.println("\n" + "Okay, the song won't be removed");
} else {
System.out.println("\n" + "Invalid option.");
}
}
}
catch (ArrayIndexOutOfBoundsException x) {
System.out.println("Please select an valid entry");
}
}
public void clearLibrary() {
System.out.println("Confirm?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//if the user types one, this triggers the clear method.
if (confirmDelete == 1) {
songLibrary.clear();
System.out.println("\n" + "Your music library has been cleared" + "/n");
}
}
public void shuffleSongs() {
//The shuffle function shifts the location of all the elements of an
//array list. This mimics the shuffle effect of a Music player
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songLibrary, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void viewAll() {
if (songLibrary.isEmpty()) {
System.out.println("Your library is currently empty!");
} else {
System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year) " + "\n");
for (int i = 0; i < songLibrary.size(); i++) {
SongClass s = songLibrary.get(i);
s.printSong();
}
}
System.out.println("\n");
}
public void randomSong() {
int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
//uses Math.random to generate a random double between 0.0 and 1.0
//it then multiplies it by the size of the array list - 1
//The end result is that a random index of the array list is selected
System.out.println("Now Playing:");
//the selected song randomSong is then outputted
//this changes each time the randomSong method is called
SongClass s = songLibrary.get(randomSong);
s.printSong();
}
public void saveLibrary() throws FileNotFoundException {
try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
File inFile = new File("MUSIC LIBRARY.txt");
Scanner in = new Scanner(inFile);
System.out.println("Your music library has been successfully exported!\n");
pw1.println("Your Music Library");
pw1.println(" ");
pw1.println("Duration - Artist - Song - Album (Year) " + "\n");
pw1.println(" ");
for (int i = 0; i < songLibrary.size(); i++) {
System.out.println("The loop ran this many times");
System.out.println(i);
int counter = i + 1;
pw1.println(counter + ": " + songLibrary.get(i));
}
System.out.println("Loop is over, PrintWriter should close.");
pw1.close();
}
}
public void addEntry() throws NumberFormatException {
try {
int minutes = ui.getInt("How many minutes does this song last?");
int seconds = ui.getInt("How many seconds does this song last?");
String title = ui.getString("What is the title of the track?");
String artist = ui.getString("Who performs the track?");
String album = ui.getString("What album is the track from?");
int year = ui.getInt("What year was the track released?");
System.out.println("Please enter a number:");
System.out.println("\n");
SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
songLibrary.add(s);
System.out.println("Thank you!" + " " + title + " " + "was added to your library:");
} catch (NumberFormatException x) {
System.out.println(" ");
System.out.println("Year/Duration can use numbers only, please try again.");
System.out.println(" ");
}
}
}
And my user input class
package MainClass;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class UserInput{
private Scanner keyboard;
public UserInput() {
this.keyboard = new Scanner(System.in);
}
public String getString(String prompt) {
String line;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
return line;
}
public int getInt(String prompt) {
String line;
int num;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
num = Integer.parseInt(line);
return num;
}
public Date getDate(String prompt) {
String line;
SimpleDateFormat formatter;
Date date;
System.out.print(prompt + " (dd/MM/yyyy): ");
line = this.keyboard.nextLine();
formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
date = formatter.parse(line);
}
catch (ParseException ex) {
date = null;
}
return date;
}
public boolean getBoolean(String prompt) {
String line;
System.out.print(prompt + "? (Y|N)");
line = this.keyboard.nextLine();
return line.equalsIgnoreCase("Y");
}
}
"1: MainClass.SongClass#c137bc9 MainClass.SongClass#c137bc9"
This is what the default implementation of toString outputs.
You need to override toString in your SongClass:
#Override
public String toString(){
return String.format("%d:%d - %s - %s - %s - (%d)",
songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}
An alternative (which may be better if you don't want to override toString, because that method is used elsewhere) is to loop over all elements of your list and explicitly format the output by calling appropriate getters (or another method similar to your printSong method).

Categories