My code is running fine at the beginning, but in the while loop, it won't prompt the user for the next input, and is just responding with no such element exception. I have tried fixing it for at least an hour, and have had no luck. Any tips on what might be wrong with it?
public class Inventory {
public static void main(String[] args) {
Store store = new Store();
String itemName;
System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.");
boolean condition = true;
Scanner s = new Scanner(System.in);
do{
System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item");
String choice = s.next();
if(choice.equals("0")){
System.out.println("Thank you for using the Sports Inventory Application. Good bye.");
condition = false;
System.exit(0);
}
else if(choice.equals("1")){
store.addItem();
}
else if(choice.equals("2")){
System.out.println("Item Name: ");
itemName = s.nextLine();
store.displayItem(itemName);
}
else if(choice.equals("3")){
System.out.println("Item Name: ");
itemName = s.nextLine();
store.deleteItem(itemName);
}
}
while(condition == true);
}
}
results in:
Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.
Please select an option and type the option number.
0. Quit
1. Add an item
2. Display stock for an item
3. Discontinue an item
1
Item Name:
test
Item Amount:
120
Item added. Information: test
Current amount in inventory is: 120
Please select an option and type the option number.
0. Quit
1. Add an item
2. Display stock for an item
3. Discontinue an item
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Inventory.main(Inventory.java:24)
EDIT: Here are the other classes of the program:
import java.util.ArrayList;
import java.util.Scanner;
public class Store {
private ArrayList<Item> inventory;
public Store(){
inventory = new ArrayList<Item>();
}
public void addItem(){
Item newItem;
int itemAmount;
String itemName;
Scanner input = new Scanner(System.in);
System.out.println("Item Name: ");
itemName = input.nextLine();
System.out.println("Item Amount: ");
itemAmount = input.nextInt();
newItem = new Item(itemName, itemAmount);
inventory.add(newItem);
System.out.println("Item added. Information: " + inventory.get(0));
input.close();
}
public void deleteItem(String itemName){
int itemIndex;
Item itemToDelete;
itemToDelete = new Item(itemName);
itemIndex = inventory.indexOf(itemToDelete);
if(itemIndex > -1){
inventory.remove(itemIndex);
}
else{
System.out.println("Item does not exist.");
}
}
public void displayItem(String itemName){
int itemIndex;
Item itemToDisplay, item;
itemToDisplay = new Item(itemName);
itemIndex = inventory.indexOf(itemToDisplay);
if (itemIndex > -1){
item = inventory.get(itemIndex);
System.out.println(item);
}
else{
System.out.println("Item does not exist.");
}
}
}
Item Class:
public class Item {
private int itemAmount;
private String itemName;
public Item(String name, int amount){
this.itemName = name;
this.itemAmount = amount;
}
public Item(String name){
itemAmount = 0;
this.itemName = name;
}
public int getItemAmount(){
return itemAmount;
}
public String getItemName(){
return itemName;
}
public String getItem(){
return itemName + itemAmount;
}
#Override
public String toString(){
String itemString;
itemString = this.itemName + "\n";
itemString += "Current amount in inventory is: " + this.itemAmount;
return itemString;
}
}
You are calling Scanner.next() without first calling Scanner.hasNext().
Scanner.next is throwing the exception because it's reached the end of file. You should end your loop when Scanner.hasNext() returns false (check at the start using a while loop.)
EDIT:
You have closed a locally-declared Scanner in method addItem(). That has the side-effect of closing the backing channel, i.e. standard input. Therefore, the scanner in your main loop can no longer get any more input - it sees a closed file.
Although it's good general advice to close whatever you open in the same method, in the case of standard input you should only ever close that your application exits.
It seems to be a problem with your code using multiple Scanner objects,
try to define a single Scanner instance and then use it all over the code (check this answer for more details: How to use multiple Scanner objects on System.in?).
Also, you missed the equals and hashCode overriding for the Item class, mandatory when calling indexOf if you want the correct object to be retrieved:
So I will post here a version that is working fine for me:
Store class:
public class Store {
private ArrayList<Item> inventory;
public Store(){
inventory = new ArrayList<>();
}
public void addItem(Scanner input){
Item newItem;
int itemAmount;
String itemName;
System.out.println("Item Name: ");
itemName = input.nextLine();
System.out.println("Item Amount: ");
itemAmount = Integer.parseInt(input.nextLine());
newItem = new Item(itemName, itemAmount);
inventory.add(newItem);
System.out.println("Item added. Information: " + inventory.get(0));
}
public void deleteItem(String itemName){
int itemIndex;
Item itemToDelete;
itemToDelete = new Item(itemName);
itemIndex = inventory.indexOf(itemToDelete);
if(itemIndex > -1){
inventory.remove(itemIndex);
}
else{
System.out.println("Item does not exist.");
}
}
public void displayItem(String itemName){
int itemIndex;
Item itemToDisplay, item;
itemToDisplay = new Item(itemName);
itemIndex = inventory.indexOf(itemToDisplay);
if (itemIndex > -1){
item = inventory.get(itemIndex);
System.out.println(item);
}
else{
System.out.println("Item does not exist.");
}
}
}
Item class:
public class Item {
private int itemAmount;
private String itemName;
public Item(String name, int amount){
this.itemName = name;
this.itemAmount = amount;
}
public Item(String name){
itemAmount = 0;
this.itemName = name;
}
public int getItemAmount(){
return itemAmount;
}
public String getItemName(){
return itemName;
}
public String getItem(){
return itemName + itemAmount;
}
#Override
public String toString(){
String itemString;
itemString = this.itemName + "\n";
itemString += "Current amount in inventory is: " + this.itemAmount;
return itemString;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Item)) return false;
Item item = (Item) o;
return itemName.equals(item.itemName);
}
#Override
public int hashCode() {
return itemName.hashCode();
}
Inventory class:
public class Inventory {
public static void main(String[] args) {
Store store = new Store();
String itemName;
System.out.println("Welcome to the Inventory Application. You can add an item, display the stock for an item, or discontinue an item.");
boolean condition = true;
Scanner s = new Scanner(System.in);
do {
System.out.println("Please select an option and type the option number." + "\n 0. Quit \n 1. Add an item \n 2. Display stock for an item \n 3. Discontinue an item");
String choice = s.nextLine();
if (choice.equals("0")) {
System.out.println("Thank you for using the Sports Inventory Application. Good bye.");
condition = false;
System.exit(0);
} else if (choice.equals("1")) {
store.addItem(s);
} else if (choice.equals("2")) {
System.out.println("Item Name: ");
itemName = s.nextLine();
store.displayItem(itemName);
} else if (choice.equals("3")) {
System.out.println("Item Name: ");
itemName = s.nextLine();
store.deleteItem(itemName);
}
}
while (condition == true);
}
}
Related
So I am trying to figure out how to get my code to work, but I keep on getting a nullError. Am I not storing my data correctly? Here is my code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
}
catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
And of course, that is the driver class, here is my object:
public class ProductPart1 {
//Declares variables
private int productNumber;
private String productName;
private int productStock;
private double productPrice;
//Constructor
public ProductPart1(){
setNumber(0);
productName = "Null";
productStock = 0;
productPrice = 0.0;
}
//Overload constructor
public ProductPart1(int number, String name, int stock, double price){
productNumber = number;
productName = name;
productStock = stock;
productPrice = price;
}
//set the number of the object
public void setNumber(int newNumber){
productNumber = newNumber;
}
//set the name of the object
public void setName(String newName){
productName = newName;
}
//set the stock of an object
public void setStock(int newStock){
productStock = newStock;
}
//set the price of an object
public void setPrice(double newPrice){
productPrice = newPrice;
}
//get the number of an object
public int getNumber(){
return getNumber();
}
//get the name of an object
public String getName(){
return productName;
}
//get the stock of an object
public int getStock(){
return productStock;
}
//get the price of an object
public double getPrice(){
return productPrice;
}
//toString to bring the object together.
public String toString(){
return new String("Number: " + getNumber() + " Name: " + productName + " Price: " + productPrice + " Stock: " + productStock);
}
try this updated code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
} catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
if(userInput.hasNext()){
line = userInput.nextLine();
} else {
break;
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
}
Your code creates an infinite loop. First you read line of product number, name, stock, and price. Then you go into a while loop, where you read this line out, but never again change the line variable, so it gets read again and again infinitely.
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();
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();
I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver
If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing
You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]
Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver
It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();
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)
}
}