How to remove objects from ArrayLists - java

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)
}
}

Related

Updating specific part of Arraylist string?

I am making a program where the person inputs multiple values and the Arraylist stores it as a single string with option 1. Option two allows you to change a specific part of that string from "Complete" to "Incomplete" and vice-versa but only if the status part of the String is one of the two. I am getting the warning "Result of 'String.replace()' is ignored" and the part of the string isn't updating. Any help would be appreciated!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Array listObj = new Array();
Scanner userinput = new Scanner(System.in);
int arraysize = (listObj.list.size());
int power = 1;
while (power < 2) {
System.out.println("To-Do List / What would you like to do?");
System.out.println("1 = Add Task / 2 = Mark Task as Done / 3 = Remove Task / 4 = Edit Task / 5 = Display Tasks / 6 = Exit");
int selection = userinput.nextInt();
if (selection == 1) {
for (int i = 0; i <= arraysize; i++) {
String title;
String date;
String status;
String description;
String id;
System.out.print("Enter Title: ");
title = userinput.next();
System.out.print("Enter Due Date: ");
date = userinput.next();
System.out.print("Enter Status (Complete or Incomplete): ");
status = userinput.next();
System.out.print("Enter Description: ");
description = userinput.next();
listObj.list.add(title + " " + date + " " + status + " " + description);
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
if (selection == 2) {
int idinput;
System.out.println("Enter Project ID to Toggle Complete/Incomplete: ");
idinput = (userinput.nextInt()-1);
System.out.println();
System.out.println(listObj.list.get(idinput));
System.out.println();
System.out.println("What is the status of this assignment?: ");
String toggleselect = userinput.next();
if (toggleselect.equals("Incomplete")) {
listObj.list.get(idinput).replace("Incomplete", "Complete");
} else if (toggleselect.equals("Complete")) {
listObj.list.get(idinput).replace("Complete", "Incomplete");
} else {
System.out.println("Status is not Complete/Incomplete");
}
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
}
}
import java.util.ArrayList;
public class Array {
ArrayList<String> list = new ArrayList<String>();
public ArrayList<String> getList() {
return list;
}
}`your text`
public String replace(char searchChar, char newChar)
demands a String to output to, as you can see by the return type. In this case use
public E set(int index, E element)
from the ArrayList library,
with E return type being your ArrayList,
and E element being your call
listObj.list.get(idinput).replace("Complete", "Incomplete");
So,
listObj.list.get(idinput).replace("Complete", "Incomplete");
becomes
listObj.list.set(idinput, listObj.list.get(idinput).replace("Complete", "Incomplete"));
Also, why are you creating a class called Array that just encapsulates an ArrayList in it?

ArrayOutOfBounds Exception (registration program)

I'm trying to write this Registration Program for Sports Teams, but when I input a name and age which qualifies for a team, an java.lang.ArrayOutOfBoundsException occurs. Any idea why? The code and classes can be seen below.
The objective of the code is to fill out arrays in the Team Class, and print it out once the user inputs '3' in the Test Class.
public class Member {
public String name;
public int age;
public Member(String name, int age){
this.name = name;
this.age = age;
}
}
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
int choi;
Team basketball = new Team("Basketball", 2, 18, 21);
Team volleyball = new Team("Volleyball", 3, 17, 19);
do{
//MENU
System.out.println("Select Team");
System.out.println("--------------");
System.out.println("[1] Basketball");
System.out.println("[2] Volleyball");
System.out.println("[3] Exit");
System.out.println("---------------");
System.out.print("Choice: ");
choi = myScan.nextInt();
myScan.nextLine();
//SWITCH START
switch(pili){
//BASKETBALL CASE
case 1:
String name;
int age;
System.out.println("Basketball");
System.out.print("Enter Name: ");
name = myScan.nextLine();
System.out.print("Enter Age: ");
age = myScan.nextInt();
myScan.nextLine();
Member bball = new Member(name,age);
basketball.addMember(bball);
break;
//END CASE 1
//VOLLEYBALL CASE
case 2:
String name1;
int age1;
System.out.println("Volleyball");
System.out.print("Enter Name: ");
name1 = myScan.nextLine();
System.out.print("Enter Age: ");
age1 = myScan.nextInt();
Member vball = new Member(name1, age1);
volleyball.addMember(vball);
break;
//END CASE 2
//EXIT CASE
case 3:
System.out.println("Basketball Team Members");
for(int i = 0; i<2; i++){
System.out.println(basketball.members[i]);
}
System.out.println("Volleyball Team Members");
for(int i = 0; i<3; i++){
System.out.println(volleyball.members[i]);
}
break;
//CASE 3 END
} //END SWITCH
} //END DO
while(choi > 0 && pili < 3);
}
public class Team {
public String name;
public int memberCnt;
public int maxMember;
public Member [] members = new Member[maxMember];
public int minAge;
public int maxAge;
public Team(String name, int maxMember, int minAge, int maxAge){
this.name = name;
this.maxMember = maxMember;
this.minAge = minAge;
this.maxAge = maxAge;
}
public void addMember(Member memb){
boolean result = checkQualification(memb);
if(memberCnt < maxMember){
if (result){
members[memberCnt]=memb;
memberCnt++;
System.out.println("Welcome to the " + name);
}
else{
System.out.println("You are not qualified!");
}
}
else{
System.out.println(name + " Team is no longer accepting applicants");
}
}
public boolean checkQualification(Member memb){
return memb.age >= minAge && memb.age <= maxAge;
}
}
The error is because of
public int maxMember;
public Member[] members = new Member[maxMember];
Because at this moment maxMember values 0, so you're creating an empty array
Do the instantiation when you have the real value of maxMembers, in the constructor
public int maxMember;
public Member[] members;
public Team(String name, int maxMember, int minAge, int maxAge) {
this.name = name;
this.maxMember = maxMember;
this.members = new Member[maxMember];
this.minAge = minAge;
this.maxAge = maxAge;
}
Attribut maxMembers could not be an attribut, and you would use array's length in condition
if (memberCnt < members.length) {

How can i use a constructor using JOptionPane to pass objects from my method into a empty array?

I'm having trouble figuring out how to store the objects from the constructor. so far all I get is one object and the remaining are all null. If someone can explain it to me so that a beginner can understand that would be much appreciated.
public class Bookstore
{
/*
Main Class Bookstore to be made modular
*/
public static void main(String args[])
{
Book catalogue[] = new Book[3];
int select;
do
{
select = bookMenu();
switch(select)
{
case 1:
int i =0;
if(catalogue[i] != null)
{
JOptionPane.showMessageDialog(null,"Test");
break;
}
catalogue[i] = addBook();
case 2:
sortBook();
break;
case 3:
searchBook(catalogue);
break;
case 4:
displayBook(catalogue);
break;
case 5:
break;
}
}
while(select != 5);
}
public static int bookMenu()
{
int select;
String menuOptions = "--Book store--\n"
+ "\n1. Add book to catalogue"
+ "\n2.Sort and display books by price"
+ "\n3. Search for a book by title"
+ "\n4. Display all books"
+ "\n\n5. Exit";
do
{
select = Integer.parseInt(JOptionPane.showInputDialog(menuOptions));
}
while(select < 1 || select > 5);
return select;
}
public static Book addBook()
{
int isbn;
String title, author;
Book catalogue = null;
double price;
for(int i=0; i<3;i++)
{
isbn = Integer.parseInt(JOptionPane.showInputDialog
("Enter Book ISBN or: "));
title = JOptionPane.showInputDialog
("Enter Book Title: ");
author = JOptionPane.showInputDialog
("Enter Book Author: ");
price = Double.parseDouble(JOptionPane.showInputDialog
("Enter Book Price: "));
catalogue = new Book(isbn, title, author, price);
}
return catalogue;
}
public static void sortBook()
{
}
public static void searchBook(Book catalogue[])//remain void
{
String searchValue = JOptionPane.showInputDialog("Enter the title of the book you are searching for");
boolean found = true;
for(int i=0; i<catalogue.length && catalogue[i] != null ; i++)
{
if(searchValue.equalsIgnoreCase(catalogue[i].getTitle()))
{
JOptionPane.showMessageDialog(null, "Book details: " + catalogue[i].toString());
found = true;
}
}
if(found == false)
JOptionPane.showMessageDialog(null, "The title does not exist in the collection ");
}
public static void displayBook(Book catalogue[])//remain void
{
String output = "";
for(Book bk:catalogue)
{
output += bk + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
So, this is always false...
if(count == max)
You set the values immediately before that statement. Zero never equals ten.
Some IDEs would even point that out to you.
If you want to get a variable that can be used between methods, you need to learn variable scoping.
For example, using a static class variable
private static Book[] books;
private static final int MAX_BOOKS = 10;
private static int count;
public static void main(String[] args) {
books = getBooks();
bookMenu();
}
public static Book[] getBooks() {
if(count == MAX_BOOKS) {
JOptionPane.showMessageDialog(null, "Catalogue full - cannot add any more books");
} else {
for(; count < MAX_BOOKS; count++) {
books[count]= addBook();
}
}
return books;
}
Then, if you want to repeat the menu, use a loop. Don't place it at the end of every method.
Also searchBook(Book) isn't searching for a title. You want to pass a string to the method, not a Book class

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();

Java Inventory - How to read a file using FileInputStream?

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()

Categories