completely basic java student here. I am having a problem with my project for AP Comp sci in which when I create an object for my cartClass in my MenuClass, I get this very long list of errors(repeats these lines over and over):
Exception in thread "main" java.lang.StackOverflowError
at ICSMenuClass.<init>(ICSMenuClass.java:27)
at ICSCartClass.<init>(ICSCartClass.java:20)
Now my other concern is the fact that when I add elements to my item and itemprice ArrayLists, they arnt stored in the ArrayList when I go to my cart class(The code is VERY messy, also im only adding items to the 'item' and 'itemprice' ArrayLists):
import java.util.*;
public class ICSMenuClass extends Objclass{
// public static void main(String[] args)
// {
//
// ICSMenuClass i1 = new ICSMenuClass();
// System.out.println(i1);
// }
ArrayList<String> ItemName = new ArrayList<String>();
ArrayList<Double> ItemPrice = new ArrayList<Double>();
public ArrayList<String> item = new ArrayList<String>();
public ArrayList<Double> itemprice = new ArrayList<Double>();
ICSCartClass icsc2 = new ICSCartClass();
ICSMenuClass icsm2 = new ICSMenuClass();
//public ArrayList<String> item = new ArrayList<String>();
//public ArrayList<Double> itemprice = new ArrayList<Double>();
//public ICSCartClass icsc1 = new ICSCartClass();
public Scanner scan = new Scanner(System.in);
public ICSMenuClass()
{
//super(item, itemprice);
//item.add("Lemon");
// this.item = item;
// this.ItemPrice = ItemPrice;
iteminfo();
}
public void iteminfo()
{
String user = "admin";
String uselessfiller = "null";
String addItem = "addItem";
String removeItem = "removeItem";
String changePrice = "changePrice";
String gocart1 = "GoCart";
//final ArrayList<String> combined = new ArrayList<String>();
//item.addAll(itemprice);
System.out.println("Who is this?");
String userused = scan.nextLine();
String viewInventory = "SeeInventory";
if(userused.equalsIgnoreCase(user))
{
int j = 1;
while(j < 2)
{
System.out.println("Would you like to edit an item? y/n");
String answer;
String yes1 = "y";
answer = scan.nextLine();
if(answer.equals(yes1))
System.out.println("What would you like to do? (Type: addItem, removeitem, changePrice, SeeInventory, GoCart)");
//scan.nextLine();
String ans1 = scan.nextLine();
//------------------------------------------------------------------------------------------------
//Add Item
//------------------------------------------------------------------------------------------------
if(ans1.equals(addItem))
{
AddItemtoInventory();
}else{
//---------------------------------------------------------------------------------------------------------------
//Remove Items
//---------------------------------------------------------------------------------------------------------------
if(ans1.equals(removeItem))
{
RemoveItemfromInventory();
}else{
//-------------------------------------------------------------------------------------------------------------
//Change Price
//-------------------------------------------------------------------------------------------------------------
if(ans1.equals(changePrice))
{
ChangePriceofItem();
}else{
//------------------------------------------------------------------------------------------------------------------------------------
//View Inventory
//------------------------------------------------------------------------------------------------------------------------------------
if(ans1.equals(viewInventory))
{
CheckInventory();
}else{
if(ans1.equals(gocart1)){
this.item = ItemName;
this.itemprice = ItemPrice;
icsm2.GotoCart();
}else{
if(ans1 == "n"){
//AccountLogin acctlogn1 = new AccountLogin();
//System.out.println(acctlogn1);
System.out.println("Ok");
}
}
} }}}}}
}
//Adding item to inventory
public void AddItemtoInventory()
{
System.out.println("Ok, how many items would you like to add?");
int i = 1;
int desireditemnumb1 = scan.nextInt();
while (i <= desireditemnumb1)
{
String filler1 = "null";
String useless1 = scan.nextLine();
useless1 = filler1;
System.out.println("Ok, enter item #" + i + " and the ISBN number after it.");
String itemname = scan.nextLine();
item.add(itemname);
System.out.println("Please add a price to the item: ");
Double itemprice1 = scan.nextDouble();
itemprice.add(itemprice1);
// System.out.println("Please set the amount of the item to add to the inventory: ");
// int i2 = scan.nextInt();
// for(int j = 0; j < i2; j++)
// {
// invAmount.add(itemname);
// }
System.out.println("Added " + itemname + " to inventory");
i++;
}
System.out.println("would you like to see your inventory?");
scan.nextLine();
String seeinventory1 = scan.nextLine();
if(seeinventory1.equals("y"))
{
System.out.println(item + "\n" + itemprice);
}else{
System.out.println("Ok...");
}
}
//Removing item method
public void RemoveItemfromInventory()
{
System.out.println("Ok, how many items would you like to remove?");
int i = 1;
int desireditemnumb1 = scan.nextInt();
while(i <= desireditemnumb1)
{
System.out.println("Ok, type the number which the item is allocated");
System.out.println(item);
int index1 = scan.nextInt();
item.remove(index1);
itemprice.remove(index1);
System.out.println("Removed " + item.get(index1) + " from inventory");
i++;
}
String yes1 = "y";
System.out.println("Would you like to see your inventory?");
String yes2 = scan.nextLine();
if(yes2.equals(yes1))
System.out.println(item + "\n" + itemprice);
}
public void ChangePriceofItem()
{
System.out.println("Ok, type the number which the item is allocated");
System.out.println(item);
int index1 = scan.nextInt();
System.out.println("Ok, now choose the price the item will cost");
double itemprice1 = scan.nextDouble();
itemprice.set(index1, itemprice1);
System.out.println("Changed price of " + item.get(index1) + " within inventory");
}
public void CheckInventory()
{
System.out.println(item + "\n" + itemprice + "\n" + invAmount);
double sum = 0;
for (double i : itemprice)
sum += i;
System.out.println("The value of the inventory: " + "$" + sum);
}
public void GotoCart()
{
System.out.println(icsc2);
}
}
And my cart class:
import java.util.*;
public class ICSCartClass extends ICSMenuClass{
public Scanner scan = new Scanner(System.in);
public ArrayList<Double> ItemPrice1 = new ArrayList<Double>();
// public static void main(String[] args)
// {
//
//
// ICSCartClass c1 = new ICSCartClass();
// System.out.println(c1);
// }
public ICSCartClass()
{
//super(item, itemprice);
addItemDefaults();
}
public void addItemDefaults()
{
ItemName.addAll(item);
ItemPrice.addAll(itemprice);
WhatDoCart();
}
public void WhatDoCart()
{
System.out.println("What do you want to do with the cart? ");
System.out.println("Plese choose the number that shows what you want to do: ");
System.out.println("Add an item = 1" + "\t\t" + "Remove an item = 2" + "\t" + "Exchange an item = 3" + "\t" + "Checkout cart = 4");
int cartans1 = scan.nextInt();
if(cartans1 == 1)
AddItemstoCart();
if(cartans1 == 2)
RemoveItemsfromCart();
if(cartans1 == 3)
ExcangeItemsinCart();
if(cartans1 == 4)
CheckoutCartNow();
}
public void AddItemstoCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to add? Press 9 to checkout.");
System.out.println(ItemName + "\n" + ItemPrice1);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = item.get(ItemAns1);
int index1 = item.indexOf(ItemAns1);
double getprice = itemprice.indexOf(index1);
cartPrice.add(getprice);
cart.add(Itemname2);
System.out.println(cart);
i++;
}
}
}
public void RemoveItemsfromCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to remove (You must have at least 2 items for checkout)? Press 9 to checkout.");
System.out.println(cart);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = cart.get(ItemAns1);
cart.remove(Itemname2);
int index1 = cartPrice.indexOf(ItemAns1);
cartPrice.remove(index1);
System.out.println(cart);
i++;
}
}
}
public void ExcangeItemsinCart()
{
int i = -1;
while(i < cart.size())
{
System.out.println("What item do you want to exchange? Press 9 to checkout.");
System.out.println(ItemName);
int ItemAns1 = scan.nextInt();
if(ItemAns1 == 9)
{
WhatDoCart();
}else{
String Itemname2 = ItemName.get(ItemAns1);
cart.set(ItemAns1, Itemname2);
System.out.println(cart);
i++;
}
}
}
public void CheckoutCartNow()
{
System.out.println(" Do you want to check out the cart now? y/n");
scan.nextLine();
String Ans1 = scan.nextLine();
if(Ans1 == "y")
{
CarttoString();
}else{
if(Ans1 == "n")
{
WhatDoCart();
}
}
}
public void CarttoString()
{
cart.clear();
//ItemAmount.add(ItemPrice);
}
}
Another error I have is when I want to got to the cart class, it takes me back to the beginning of the itemInfo() method, and I have to type anything but "Admin" in there to go to the cartClass.
Thank you for you help, and sorry about the long code, i'm not good at cropping what I need. Also, I want to know how to get my item/itemprice ArrayLists keep their elements when I go to the cart class. Thank you!
Ok, so I've done some fixes to it, but it still goes back to asking: "Who is this?" after I type GoCart. Plus the array still shows up empty.
public void iteminfo()
{
String user = "admin";
// String addItem = "addItem";
// String removeItem = "removeItem";
// String changePrice = "changePrice";
// String gocart1 = "GoCart";
//final ArrayList<String> combined = new ArrayList<String>();
//item.addAll(itemprice);
System.out.println("Who is this?");
String userused = scan.nextLine();
String viewInventory = "SeeInventory";
if(userused.equalsIgnoreCase(user))
{
int j = 1;
while(j < 2)
{
System.out.println("Would you like to edit an item? y/n");
String answer;
//String yes1 = "y";
answer = scan.nextLine();
if(answer.equals("y"))
System.out.println("What would you like to do? (Type: addItem, removeitem, changePrice, SeeInventory, GoCart)");
//scan.nextLine();
String ans1 = scan.nextLine();
//------------------------------------------------------------------------------------------------
//Add Item
//------------------------------------------------------------------------------------------------
if(ans1.equals("addItem"))
{
AddItemtoInventory();
}else{
//---------------------------------------------------------------------------------------------------------------
//Remove Items
//---------------------------------------------------------------------------------------------------------------
if(ans1.equals("removeItem"))
{
RemoveItemfromInventory();
}else{
//-------------------------------------------------------------------------------------------------------------
//Change Price
//-------------------------------------------------------------------------------------------------------------
if(ans1.equals("changePrice"))
{
ChangePriceofItem();
}else{
//------------------------------------------------------------------------------------------------------------------------------------
//View Inventory
//------------------------------------------------------------------------------------------------------------------------------------
if(ans1.equals("SeeInventory"))
{
CheckInventory();
}else{
if(ans1.equals("GoCart")){
j++;
this.item = ItemName;
this.itemprice = ItemPrice;
GotoCart();
}else{
if(ans1 == "n"){
//AccountLogin acctlogn1 = new AccountLogin();
//System.out.println(acctlogn1);
System.out.println("Ok");
break;
}
}
}
}
}
}
}
}
}
When you are initializing your J in the iteminfo() method ICSMenuClass. You are not decrementing it in your function any where. Which means that your loop would never end while(j < 2) would always be true.
There are many useless variables declared which makes it hard to understand the flow, e.g.
String yes1 = "y";
You can do if(answer.equals("y")) to avoid the extra variable being declared.
Related
The program should contain the customers plus a list of the calories and the distance during the week.
My question is, how can I put together the customer's name and the distance?
public class TestCustomer {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> customersNames = new ArrayList<String>();
char userInput = ' ';
System.out.println("A to show all");
userInput = scan.next().charAt(0);
if(userInput == 'A') {
System.out.println("All results ");
for(int i = 0; i < customersNames.size(); i++) {
System.out.println(customersNames.get(i));
}
}
}
And here's my Customer class
public class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double distance) {
this.name = name;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return distance;
}
}
This uses a list of customers instead of customernames.
I put the Customer class as static in the testclass for brevity(keep everything in one file). Better to have it seperate as you do.
Also I did not want to change the whole design or do a complete rewrite - it is your design. So this is only making it work, fixing the behavior to the one required.
Eg with having the customers in HashMap that is indexed by name one could retrieve a dataset more elegantly in O(1). But thats maybe another improvement.
This only has the list. So for simplicity I added an equals, that makes users equal if they have the same name.
I create a new User that can be searched in the list. If not found I add this user with the given input to the list.
If found I search for existing the user in the list with indexOf and retrieve that existing user. I do it in one step.
import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;
public class TestCustomer {
public static class Customer {
private String name;
private double calories;
private double distance;
public Customer(String name, double calories, double distance) {
this.name = name;
this.calories = calories;
this.distance = distance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCalories(double calories) {
this.calories = calories;
}
public double getCalories() {
return calories;
}
public void setDistance(double distance) {
this.distance = distance;
}
public double getDistance() {
return this.distance;
}
#Override
public int hashCode() {
int hash = 5;
hash = 71 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return Objects.equals(this.name, ((Customer)obj).name);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Customer> customers = new ArrayList<>();
char userInput = ' ';
while (userInput != 'q') {
System.out.println("Press 'a' to show all customers or press 's' to search for customer ");
userInput = scan.next().charAt(0);
userInput = Character.toUpperCase(userInput);
if (userInput == 'A') {
System.out.println("Here's the list of all customers: ");
for (int i = 0; i < customers.size(); i++) {
System.out.println(customers.get(i).getName());
}
// here I should show the list of all customers and their data
} else if (userInput == 'S') {
System.out.println("You selected to search for a customer");
createCustomer(customers);
}
}
}
public static ArrayList<Customer> createCustomer(ArrayList<Customer> customers) {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter customer's first name: ");
String fName = scan2.next();
System.out.println("Enter customer's last name: ");
String lName = scan2.next();
String fullName = fName + " " + lName;
Customer newCustomer = new Customer(fullName,0,0);
if (customers.contains(newCustomer)) {
newCustomer=customers.get(customers.indexOf(newCustomer));
System.out.println("Customer already on the list. Here's the information: ");
System.out.println(fullName + " " + newCustomer.distance + " " + newCustomer.calories );
} else{
System.out.println("Customer not found. Would you like to create a new customer? y/n ");
char createUserPrompt = scan2.next().charAt(0);
if (createUserPrompt == 'y') {
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (String daysOfWeek1 : daysOfWeek) {
System.out.println("Enter calories consumed on " + daysOfWeek1);
newCustomer.calories = scan2.nextDouble();
System.out.println("Enter distance walked on " + daysOfWeek1);
newCustomer.distance = scan2.nextDouble();
}
customers.add(newCustomer);
} else if (createUserPrompt == 'n') {
System.out.println("User will not be added.");
}
}
return customers;
}
}
sample run:
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer not found. Would you like to create a new customer? y/n
y
Enter calories consumed on Monday
5
Enter distance walked on Monday
5
Enter calories consumed on Tuesday
5
Enter distance walked on Tuesday
5
Enter calories consumed on Wednesday
5
Enter distance walked on Wednesday
5
Enter calories consumed on Thursday
5
Enter distance walked on Thursday
5
Enter calories consumed on Friday
5
Enter distance walked on Friday
5
Enter calories consumed on Saturday
5
Enter distance walked on Saturday
5
Enter calories consumed on Sunday
5
Enter distance walked on Sunday
5
Press 'a' to show all customers or press 's' to search for customer
a
Here's the list of all customers:
kai last
Press 'a' to show all customers or press 's' to search for customer
s
You selected to search for a customer
Enter customer's first name:
kai
Enter customer's last name:
last
Customer already on the list. Here's the information:
kai last 5.0 5.0
Press 'a' to show all customers or press 's' to search for customer
With some modifications to your Customer class in which the calories and distance will be stored ad an array for each day,
An ArrayList<Customer> will be used to store the list of customers.
Possible solution:
import java.util.*;
public class Main {
private static Scanner scan;
private static ArrayList<Customer> customers;
public static Customer customerExists(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if (customers.get(i).getName().equals(customerName)) {
return customers.get(i);
}
}
return null;
}
public static void addCustomer() {
System.out.println(">> Add Customer <<\n");
System.out.print("Enter customer's first name: ");
String fName = scan.nextLine();
System.out.print("Enter customer's last name: ");
String lName = scan.nextLine();
String fullName = fName + " " + lName;
Customer existingCustomer = customerExists(fullName);
if (existingCustomer != null) {
System.out.println("\nCustomer already on the list. Here's the information: ");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(existingCustomer.getName() + "\t" + Arrays.toString(existingCustomer.getCalories()) + "\t" + Arrays.toString(existingCustomer.getDistance()));
return;
}
String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
double calories[] = new double[daysOfWeek.length];
double distance[] = new double[daysOfWeek.length];
for (int j = 0; j < daysOfWeek.length; j++) {
System.out.print("Enter calories consumed on " + daysOfWeek[j] + ": ");
calories[j] = scan.nextDouble();
System.out.print("Enter distance walked on " + daysOfWeek[j] + ": ");
distance[j] = scan.nextDouble();
}
Customer customer = new Customer(fullName, calories, distance);
customers.add(customer);
System.out.println("\nCustomer added successfully!\n");
}
public static void showCustomers() {
System.out.println(">> All Customers <<\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
for (int i = 0; i < customers.size(); i++) {
System.out.println(i+1 + "\t" + customers.get(i).getName() + "\t" + Arrays.toString(customers.get(i).getCalories()) + "\t\t\t" + Arrays.toString(customers.get(i).getDistance()));
}
System.out.println("\n");
}
public static void searchCustomers() {
System.out.println(">> Search for a Customer <<\n");
System.out.print("Enter customer's full name: ");
String fullName = scan.nextLine();
Customer customer = customerExists(fullName);
System.out.println(fullName);
if (customer == null) {
System.out.println("\nNo such customer exists.\n");
return;
}
System.out.println("\nCustomer information:\n");
System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
System.out.println(customer.getName() + "\t" + Arrays.toString(customer.getCalories()) + "\t" + Arrays.toString(customer.getDistance()) + "\n");
}
public static void main(String[] args) {
boolean cont = true;
int option = -1;
scan = new Scanner(System.in);
customers = new ArrayList<>();
do {
System.out.println("=== Select an Option ===");
System.out.println("1. Add a customer");
System.out.println("2. Show all customers");
System.out.println("3. Search for customer");
System.out.println("0. Exit");
System.out.print("\n > ");
try {
option = Integer.parseInt(scan.nextLine());
System.out.println("\n");
switch(option) {
case 1:
addCustomer();
break;
case 2:
showCustomers();
break;
case 3:
searchCustomers();
break;
case 0:
System.out.println("Good Bye!");
cont = false;
break;
default:
System.err.println("'" + option + "' is not a valid option. Please try again.\n");
break;
}
} catch (NumberFormatException e) {
System.err.println("Invalid option selected.\n");
}
} while (cont == true);
}
}
I have created an array of 25 Flower objects. Each flower object holds the flower name(String), flower color(String), presence of thorns(boolean), and flower scent(String). These attributes are handled by the 'Flower' class. I have pasted both classes in case the error is being caused by either class. The user inputs all of the attributes of the flowers when the menu prompts for the information. After the user enters all of the flowers they want to, I need to be able to print out the entire array and a counter of how many of each flower there are. For instance, if the user puts in 10 flowers and there are 3 Roses, 2 Lilly's, 3 Dandelions, and 2 Orchids, I need to print the entire array and then print the number each flower was present. The format for the display is:
Flower name: Rose Flower color: Red Flower has thorns: true Flower scent: Sweet
Rose - 3
Lilly - 3
Dandelion - 3
Orchid - 2
I am able to print out the array as shown, but cannot get the count variable to work properly. I do not need to sort this array.
Another issue I am getting in an OutOfBounds error. I can only put in 24 flowers before I encounter this error. The 25th flower triggers it. I thought this was covered by the addFlower index counter, but obviously, I was incorrect.
This assignment does not allow the use of ArrayList, which would make this much simpler. We have not explored error handling yet either.
Current code is:
package assignment2;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
new Assignment2();
}
public Assignment2()
{
Scanner input = new Scanner(System.in);
Flower flowerPack[] = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while (true)
{
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice)
{
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
input.close();
System.exit(0);
}
}
}
private void addFlower(Flower flowerPack[])
{
String flowerName; // Type of flower
String flowerColor; // Color of the flower
Boolean hasThorns = false; // Have thorns?
String flowerScent; // Smell of the flower
int index = 0;
Scanner input = new Scanner(System.in);
System.out.println("What is the name of flower is it?");
flowerName = input.nextLine();
System.out.println("What color is the flower?");
flowerColor = input.nextLine();
System.out.println("Does the flower have thorns?");
System.out.println("Choose 1 for yes, 2 for no");
int thorns = input.nextInt();
if(thorns == 1)
{
hasThorns = true;
}
input.nextLine();
System.out.println("What scent does the flower have?");
flowerScent = input.nextLine();
Flower fl1 = new Flower(flowerName, flowerColor, hasThorns, flowerScent);
for(int i = 0; i < flowerPack.length; i++)
{
if(flowerPack[i] != null)
{
index++;
if(index == flowerPack.length)
{
System.out.println("The pack is full");
}
}
else
{
flowerPack[i] = fl1;
break;
}
}
}
private void removeFlower(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
System.out.println("What student do you want to remove?");
displayFlowers(flowerPack);
System.out.println("Choose 1 for the first flower, 2 for the second, etc" );
int index = input.nextInt();
index = index - 1;
for (int i = 0; i < flowerPack.length - 1; i++)
{
if(flowerPack[i] != null && flowerPack[i].equals(flowerPack[index]))
{
flowerPack[i] = flowerPack[i + 1];
}
}
}
private void searchFlowers(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
String name;
System.out.println("What flower would you like to search for?");
name = input.nextLine();
boolean found = false;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i].getFlowerName().equalsIgnoreCase(name))
{
found = true;
break;
}
}
if (found)
{
System.out.println("We found your flower.");
}
else
{
System.out.println("That flower was not found.");
}
}
private void displayFlowers(Flower flowerPack[])
{
int count = 1;
for(int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
if (flowerPack[i].equals(flowerPack[i+1]))
{
count++;
}
else
{
System.out.println(flowerPack[i]);
count = 1;
}
}
else
{
if (flowerPack[i] == null)
{
break;
}
}
}
}
}
The Flower class is below.
package assignment2;
public class Flower
{
#Override
public String toString()
{
return "Flower name: " + this.getFlowerName() + "\t" +
"Flower color: " + this.getFlowerColor() + "\t" +
"Flower has thorns: " + this.getHasThorns() + "\t" +
"Flower scent: " + this.getFlowerScent() + "\t" ;
}
private String flowerName;
private String flowerColor;
private Boolean hasThorns;
private String flowerScent;
Flower(String flowerName, String flowerColor, Boolean hasThorns, String flowerScent)
{
this.flowerName = flowerName;
this.flowerColor = flowerColor;
this.hasThorns = hasThorns;
this.flowerScent = flowerScent;
}
String getFlowerName()
{
return flowerName;
}
private void setFlowerName(String flowerName)
{
this.flowerName = flowerName;
}
private String getFlowerColor()
{
return flowerColor;
}
private void setFlowerColor()
{
this.flowerColor = flowerColor;
}
private Boolean getHasThorns()
{
return hasThorns;
}
private void setHasThorns()
{
this.hasThorns = hasThorns;
}
private String getFlowerScent()
{
return flowerScent;
}
private void setFlowerScent()
{
this.flowerScent = flowerScent;
}
}
private void displayFlowers(Flower flowerPack[])
{
String[] usedNames = new String[flowerPack.length];
int[] nameCounts = new int[flowerPack.length];
int usedNamesCount = 0;
for (int i = 0; i < flowerPack.length; i++)
{
Flower flower = flowerPack[i];
if (flower == null)
{
continue;
}
int nameIndex = -1;
for (int j = 0; j < usedNamesCount; j++)
{
String usedName = usedNames[j];
if (flower.getFlowerName().equals(usedName))
{
nameIndex = j;
break;
}
}
if (nameIndex != -1)
{
nameCounts[nameIndex] += 1;
}
else
{
usedNames[usedNamesCount] = flower.getFlowerName();
nameCounts[usedNamesCount] += 1;
usedNamesCount++;
}
}
for (int i = 0; i < usedNamesCount; i++)
{
System.out.println(usedNames[i] + "s - " + nameCounts[i]);
}
}
I'm currently a beginner student in computer science, and I have been working on a "Movie Library" application for class. In my original code it seems as though whenever I call the .printLibrary() and .averageRating() methods there is nothing that prints out, even though I have initialized the array objects and input new information into them.
public class MovieApp {
public static void main(String [] args) {
MovieUX mu = new MovieUX();
mu.run();
}
}
import java.util.Scanner;
public class MovieUX {
public void run(){
Scanner input = new Scanner (System.in);
char continueProcess = 'y';
while(continueProcess == 'y'){
System.out.println(" Welcome to the Movie Data Base");
System.out.println("-----------------------------------------------");
System.out.println("Please select from the following options: (Please make sure to create your library"+
" and movie(s) first.)");
System.out.println("1. Create a library.");
System.out.println("2. Create a Movie.");
System.out.println("3. Add a movie to a library.");
System.out.println("4. Add an actor to a movie.");
System.out.println("5. Print a library.");
System.out.println("6. Print average movie rating for a library.");
System.out.println("-----------------------------------------------");
int option = input.nextInt();
int i = 0;
int j = 0;
Library [] libraryArr = new Library[10];
for(int a=0; a<libraryArr.length; a++)
libraryArr[a] = new Library(0);
Movie [] movieArr = new Movie[10];
for(int b=0; b<movieArr.length; b++)
movieArr[b] = new Movie("","",0,0.0,0);
switch (option){
case 1:
System.out.println("Please input the amount of movies in your library");
int numOfMovies = input.nextInt();
libraryArr [i] = new Library(numOfMovies);
i++;
break;
case 2:
System.out.println("Please enter the name of the movie");
String title = input.next();
System.out.println("Please enter the director of the movie");
String director = input.next();
System.out.println("Please enter the year the movie was released");
int year = input.nextInt();
System.out.println("Please enter the movie's rating");
double rating = input.nextDouble();
System.out.println("Please enter the number of actors");
int maxActors = input.nextInt();
movieArr [j] = new Movie(title, director, year, rating, maxActors);
j++;
break;
case 3:
System.out.println("Below is your list of movies, select the corresponding movie" +
" to add it to your desired library.");
System.out.println();
for(int k=0; k<movieArr.length; k++){
System.out.println((k)+". "+movieArr[k].getTitle());
}
int movieChoice = input.nextInt();
System.out.println("Below are some libraries, chose the library that you wish to" +
" add your movie into.");
System.out.println();
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
int desiredLibrary = input.nextInt();
libraryArr[desiredLibrary].addMovie(movieArr[movieChoice]);
break;
case 4:
System.out.println("Below is your list of movies, please select the movie"+
" that you desire to add an actor into.");
System.out.println();
for(int k=0; k<movieArr.length; k++){
System.out.println((k)+". "+movieArr[k].getTitle());
}
movieChoice = input.nextInt();
System.out.println("Please input the actor's name that you would like to"+
" add to your movie.");
String addedActor = input.next();
movieArr[movieChoice].addActor(addedActor);
break;
case 5:
System.out.println("To print out a library's contents, please select from the following"+
" list.");
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
desiredLibrary = input.nextInt();
libraryArr[desiredLibrary].printLibrary();
break;
case 6:
System.out.println("To print out the average movie rating for a library, please"+
" select a library from the following list.");
for(int l=0; l<libraryArr.length; l++){
System.out.println("Library #" +(l));
}
desiredLibrary = input.nextInt();
System.out.println(libraryArr[desiredLibrary].averageRating());
break;
default:
System.out.println("Not a valid input.");
}
System.out.println("If you would like to continue customizing and adjusting your library"+
" and movie settings, please input 'y'. Otherwise, press any key and hit 'enter'.");
continueProcess = input.next().charAt(0);
}
}
}
import java.util.Arrays;
public class Movie {
private String title;
private String director;
private int year;
private double rating;
private String [] actors;
private int numberOfActors;
public Movie(String title, String director, int year, double rating, int maxActors) {
this.title = title;
this.director = director;
this.year = year;
this.rating = rating;
actors = new String[maxActors];
numberOfActors = 0;
}
public String getTitle() {
return title;
}
public String getDirector() {
return director;
}
public int getYear() {
return year;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public String [] getActors() {
return Arrays.copyOf(actors, actors.length);
}
public boolean addActor(String actor) {
if (numberOfActors < actors.length) {
actors[numberOfActors] = actor;
numberOfActors++;
return true;
}
return false;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Title: " + title + "\n");
sb.append("Director: " + director + "\n");
sb.append("Year: " + year + "\n");
sb.append("Rating: " + rating + "\n");
sb.append("Starring:\n");
for (int i=0; i<numberOfActors; i++)
sb.append("\t" + actors[i] + "\n");
return sb.toString();
}
}
public class Library {
private Movie [] movies;
private int numberOfMovies;
public Library(int maxMovies) {
movies = new Movie[maxMovies];
numberOfMovies = 0;
}
public int getNumberOfMovies() {
return numberOfMovies;
}
public boolean addMovie(Movie movie) {
if (numberOfMovies < movies.length) {
movies[numberOfMovies] = movie;
numberOfMovies++;
return true;
}
return false;
}
public double averageRating() {
double total = 0.0;
for (int i=0; i<numberOfMovies; i++)
total += movies[i].getRating();
return total / numberOfMovies;
}
public void printLibrary() {
for (int i=0; i<numberOfMovies; i++)
System.out.println(movies[i]);
}
}
I was wondering, was the reason why when I call the .printLibrary() and .averageRating() methods in Switch Case #5 and #6 respectively of Class MovieUX do not print anything because they are embedded in a switch statement, and information is not stored whenever the program processes the switch statement, or some other reason?
Thank you all for your help.
replace printLibrary() method with:
public void printLibrary() {
System.out.println(numberOfMovies);
for (int i=0; i<numberOfMovies; i++)
System.out.println(movies[i]);
}
you will find it output:
0
and so the for loop cant be executed. and
the same as averageRating()
Below is my code, and there are no errors in the actual code, but it won't run and I am not sure how to fix it. I have been working on this assignment for hours and keep receiving the same error in the output box over and over.
import java.util.Scanner;
public class whatTheGerbils
{
public static void main(String[] args)
{
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
Gerbil[] gerbilArray;
Food[] foodArray;
int numGerbils;
int foodnum;
public whatTheGerbils() {}
public void gerbLab()
{
boolean gerbLab = true;
while(gerbLab)
{
foodnum = 0;
numGerbils = 0;
String nameOfFood = "";
String colorOfFood;
int maxAmount = 0;
String ID;
String name;
String onebite;
String oneescape;
boolean bite = true;
boolean escape = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
int foodnum = Integer.parseInt(keyboard.nextLine());
foodArray = new Food[foodnum];
for (int i = 0; i < foodnum; i++)
{
System.out.println("The name of food item " + (i+1) + ":"); //this is different
nameOfFood = keyboard.nextLine();
System.out.println("The color of food item " + (i+1) + ":");
colorOfFood = keyboard.nextLine();
System.out.println("Maximum amount consumed per gerbil:");
maxAmount = keyboard.nextInt();
keyboard.nextLine();
foodArray[i] = new Food(nameOfFood, colorOfFood, maxAmount);
}
System.out.println("How many gerbils are in the lab?");
int numGerbils = Integer.parseInt(keyboard.nextLine()); // this is different
gerbilArray = new Gerbil[numGerbils];
for (int i = 0; i < numGerbils; i++)
{
System.out.println("Gerbil " + (i+1) + "'s lab ID:");
ID = keyboard.nextLine();
System.out.println("What name did the undergrads give to "
+ ID + "?");
name = keyboard.nextLine();
Food[] gerbsBetterThanMice = new Food[foodnum];
int foodType = 0;
for(int k = 0; k < foodnum; k++)
{
boolean unsound = true;
while(unsound)
{
System.out.println("How much " + foodArray[k].getnameOfFood() + "does" + name + " eat?");
foodType = keyboard.nextInt();
keyboard.nextLine();
if(foodType <= foodArray[k].getamtOfFood())
{
unsound = false;
}
else
{
System.out.println("try again");
}
}
gerbsBetterThanMice[k] = new Food(foodArray[k].getnameOfFood(), foodArray[k].getcolorOfFood(), foodType);
}
boolean runIt = true;
while (runIt)
{
System.out.println("Does " + ID + "bite? (Type in True or False)");
onebite = keyboard.nextLine();
if(onebite.equalsIgnoreCase("True"))
{
bite = true;
runIt = false;
}
else if (onebite.equalsIgnoreCase("False"))
{
bite = false;
runIt = false;
}
else {
System.out.println("try again");
}
}
runIt = true;
while(runIt)
{
System.out.println("Does " + ID + "try to escape? (Type in True or False)");
oneescape = keyboard.nextLine();
if(oneescape.equalsIgnoreCase("True"))
{
escape = true;
runIt = false;
}
else if(oneescape.equalsIgnoreCase("False"))
{
escape = false;
runIt = false;
}
else
{
System.out.println("try again");
}
}
gerbilArray[i] = new Gerbil(ID, name, bite, escape, gerbsBetterThanMice);
}
for(int i = 0; i < numGerbils; i++)
{
for(int k = 0; k < numGerbils; k++)
{
if(gerbilArray[i].getID().compareTo(gerbilArray[k].getID()) >
0)
{
Gerbil tar = gerbilArray[i];
gerbilArray[i] = gerbilArray[k];
gerbilArray[k] = tar;
}
}
}
boolean stop = false;
String prompt = "";
while(!stop)
{
System.out.println("Which function would you like to carry out: average, search, restart, or quit?");
prompt = keyboard.nextLine();
if (prompt.equalsIgnoreCase("average"))
{
System.out.println(averageFood());
}
else if (prompt.equalsIgnoreCase("search"))
{
String searchForID = "";
System.out.println("What lab ID do you want to search for?");
searchForID = keyboard.nextLine();
Gerbil findGerbil = findThatRat(searchForID);
if(findGerbil != null)
{
int integer1 = 0;
int integer2 = 0;
for (int i = 0; i < numGerbils; i++)
{
integer1 = integer1 + foodArray[i].getamtOfFood();
integer2 = integer2 + findGerbil.getGerbFood()[i].getamtOfFood();
}
System.out.println("Gerbil name: " +
findGerbil.getName() + " (" + findGerbil.getBite() + ", " +
findGerbil.getEscape() + ") " +
Integer.toString(integer2) + "/" + Integer.toString(integer1));
}
else
{
System.out.println("error");
}
}
else if (prompt.equalsIgnoreCase("restart"))
{
stop = true;
break;
}
else if(prompt.equalsIgnoreCase("quit"))
{
System.out.println("program is going to quit");
gerbLab = false;
stop = true;
keyboard.close();
}
else
{
System.out.println("error, you did not type average, search, restart or quit");
}
}
}
}
public String averageFood()
{
String averageStuff = "";
double avg = 0;
double num1 = 0;
double num2 = 0;
for (int i = 0; i < numGerbils; i++)
{
averageStuff = averageStuff + gerbilArray[i].getID();
averageStuff = averageStuff + " (";
averageStuff = averageStuff + gerbilArray[i].getName();
averageStuff = averageStuff + ") ";
for (int k = 0; k < foodnum; k++)
{
num1 = num1 + foodArray[k].getamtOfFood();
num2 = num2 + gerbilArray[i].getGerbFood()[k].getamtOfFood();
}
avg = 100*(num2/num1);
avg = Math.round(avg);
averageStuff = averageStuff + Double.toString(avg);
averageStuff = averageStuff + "%\n";
}
return averageStuff;
}
public Gerbil findThatRat (String ID)
{
for(int i = 0; i < numGerbils; i++)
{
if(ID.contentEquals(gerbilArray[i].getID()))
{
return gerbilArray[i];
}
}
return null;
}
}
Whenever a Java program runs, it starts with a method called main. You are getting the error because you don't have such a method. If you write such a method, then what it needs to do is this.
Create an object of the whatTheGerbils class.
Run the gerbLab() method for the object that was created.
The simplest way to do this would be to add the following code inside the whatTheGerbils class.
public static void main(String[] args){
whatTheGerbils toRun = new whatTheGerbils();
toRun.gerbLab();
}
You need a main method in your code for it to run, add in something like this
public static void main(String [] args){
gerLab();
}
I am doing my Java homework for a class. I wrote the below store program that the user inputs a 4 digit id and what money they had for that store id. This information get's put in an array. totals and store id's are retrieved.
in the next part of my program I am to retrieve min and max values from each data group:even and odd store id numbers. I have tried to do this by retrieving the origonal data and putting them into a new array. even data into an even array and odd data into an odd array. in the following code I am testing the even part. Once it works I will replicate in the odd section.
Right now the following code skips my request. I don't know how to fix this.
Any insight would be greatly appreciated!
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Bonus
{
public static void main (String[] arg)
{
Scanner in = new Scanner(System.in);
String storeID, highID;
double grandTotalSales = 0;
double evenGrandTotal = 0;
double oddGrandTotal = 0;
double evenTotalSale;
double oddTotalSale;
double largestYet = 0;
double maxValue = 0;
int numPenn, numNick, numDime, numQuar, numHalf, numDol;
boolean more = true;
boolean report = true;
String input;
int inputopt;
char cont;
char check1, highStoreID;
Store myStore;
ArrayList<Store> storeList = new ArrayList<Store>();
ArrayList<Store> evenStoreList = new ArrayList<Store>();
while(more)
{
in = new Scanner(System.in);
System.out.println("Enter 4 digit store ID");
storeID = in.nextLine();
System.out.println("Enter num of Penny");
numPenn = in.nextInt();
System.out.println("Enter num of Nickel");
numNick = in.nextInt();
System.out.println("Enter num of Dime");
numDime = in.nextInt();
System.out.println("Enter num of Quarter");
numQuar = in.nextInt();
System.out.println("Enter num of Half dollars");
numHalf = in.nextInt();
System.out.println("Enter num of Dollar bills");
numDol = in.nextInt();
myStore = new Store(storeID, numPenn, numNick, numDime, numQuar, numHalf, numDol);
storeList.add(myStore);
in = new Scanner(System.in);
System.out.println("More stores: Yes or No");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'N')||(cont == 'n'))
more = false;
}
while(report)
{
in = new Scanner(System.in);
System.out.println("What would you like to do? \nEnter: \n1 print Odd Store ID's report \n2 print Even Store ID's report \n3 to Exit");
inputopt = in.nextInt();
if(inputopt == 2)
{
System.out.println("\nEven Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + "Even Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '0' || check1 == '2' || check1 == '4'|| check1 == '6' || check1 =='8')
{
myStore.findEvenValue();
evenTotalSale = myStore.getEvenValue();
evenGrandTotal = evenGrandTotal + Store.getEvenValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getEvenValue() + " | " + (storeList.get(i)).getEvenGrandValue());
}
}
in = new Scanner(System.in);
System.out.println("Do want to print the highest and lowest sales? \nEnter yes or no");
input = in.nextLine();
cont = input.charAt(0);
if((cont == 'Y')||(cont == 'y'))
{
evenTotalSale = 0;
for(int i = 1; i < evenStoreList.size(); ++i)
{
myStore = (Store)(evenStoreList.get(i));
highID = myStore.getStoreID();
myStore.findEvenValue();
largestYet = myStore.getEvenValue();
if(largestYet > evenTotalSale)
{
Collections.copy(storeList, evenStoreList);
System.out.println("Store ID with highest sales is: ");
System.out.println((evenStoreList.get(i)).getStoreID() + " | " + largestYet);
}
}
}
else if((cont == 'N')||(cont == 'n'))
report = true;
}
else
if(inputopt == 1)
{
System.out.println("\nOdd Store ID's Report:");
System.out.println("Store ID" + " | " + " Total Sales" + " | " + " Odd Total Sales");
for(int i = 0; i < storeList.size(); ++i)
{
myStore = (Store)(storeList.get(i));
storeID = myStore.getStoreID();
check1 = storeID.charAt(3);
if(check1 == '1' || check1 == '3' || check1 == '5'|| check1 == '7' || check1 =='9')
{
myStore.findOddValue();
oddTotalSale = myStore.getOddValue();
oddGrandTotal = oddGrandTotal + Store.getOddValue();
System.out.println((storeList.get(i)).getStoreID() + " | " + (storeList.get(i)).getOddValue() + " | " + (storeList.get(i)).getOddGrandValue());
}
}
}
else
if(inputopt == 3)
report = false;
} // close while report
}// close of main
} // close class
class store:
public class Store
{
private String storeID;
private int numPenn, numNick, numDime, numQuar, numHalf, numDol;
Coin penn = new Coin("Penn", 0.01);
Coin nick = new Coin("Nickel", 0.05);
Coin dime = new Coin("Dime", 0.10);
Coin quar = new Coin("Quar", 0.25);
Coin half = new Coin("Half", 0.50);
Coin dol = new Coin("Dollar", 1.00);
private static double evenTotalSale;
private static double oddTotalSale;
static double evenGrandTotal = 0;
static double oddGrandTotal = 0;
public Store (String storeID, int numPenn, int numNick, int numDime, int numQuar, int numHalf, int numDol)
{
this.storeID = storeID;
this.numPenn = numPenn;
this.numNick = numNick;
this.numDime = numDime;
this.numQuar = numQuar;
this.numHalf = numHalf;
this.numDol = numDol;
}
public void findEvenValue()
{ evenTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
evenGrandTotal = evenGrandTotal + evenTotalSale;
}
public static double getEvenValue()
{
return evenTotalSale;
}
public void findOddValue()
{ oddTotalSale = numPenn * penn.getValue() + numNick * nick.getValue() + numDime * dime.getValue()
+ numQuar * quar.getValue() + numHalf * half.getValue() + numDol * dol.getValue();
oddGrandTotal = oddGrandTotal + oddTotalSale;
}
public static double getOddValue()
{
return oddTotalSale;
}
public static double getOddGrandValue()
{
return oddGrandTotal;
}
public static double getEvenGrandValue()
{
return evenGrandTotal;
}
public String getStoreID()
{
return storeID;
}
}
your evenStoreList is empty.