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]);
}
}
Related
I need my program to detect previous entries in it's contact list and negate the user from inputting two identical entries. I keep trying, but I either allow every entry, or the entry that's invalid is still saved to my list.
What I want is to make it so my program will be a phone book, and no two people in real life should have the same number. This is why I want there to be only one contact with any given number.
Here's my code for checking the entry:
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
}
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
return;
}else{
break;
}
}
contactList[num_entries].number = number;
Here's my full code for reference:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
class Entry {
public String fname, lname, number, note;
}
class PBN {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
Scanner s = new Scanner(System.in);
int i;
char C;
String code, Command;
contactList = new Entry[999];
num_entries = 0;
try {
readPhoneBook("PhoneBook.txt");
} catch (FileNotFoundException e) {}
System.out.println("Codes are entered as 1 to 8 characters.\n" +
"Use Commands:\n" +
" \"e\" for enter a new contact,\n" +
" \"f\" for find contact by fist name,\n" +
" \"r\" for find contact by last name,\n" +
" \"y\" for find contact by phone number,\n" +
" \"l\" for listing all the existing contacts,\n" +
" \"d\" for removing contacts by phone number,\n" +
" \"a\" for sort alphabetically by first name,\n" +
" \"n\" for sort alphabetically by last name,\n" +
" \"p\" for sort by number,\n" +
" \"q\" to quit.");
Command = null;
C = ' ';
while(true) { // loop infinitely
System.out.print("Command: ");
Command = stdin.nextLine();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
System.out.print("Search for contact by first name: ");
code = stdin.next();
stdin.nextLine();
index(code); break;
case 'r':
System.out.print("Search for contact by last name: ");
code = stdin.next();
stdin.nextLine();
index1(code); break;
case 'y':
System.out.print("Search for contact by phone number: ");
code = stdin.next();
stdin.nextLine();
index2(code); break;
case 'l':
listAllContacts(); break;
case 'q': // when user wants to quit
CopyPhoneBookToFile("PhoneBook.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt");
System.exit(0); // simply terminate the execution
case 'a':
sortList1();
break;
case 'n':
sortList2();
break;
case 'p':
sortListByPhoneNumber();
break;
case 'd': // m for deleting a contact; delete by phone number
System.out.print("Enter the phone number of a contact you wish to delete : ");
String number = stdin.nextLine();// read the contact number
removeEntry1(number); // remove the number from the entries
break;
default:
System.out.println("Invalid command Please enter the command again!!!");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter first name: ");
String fname = stdin.nextLine();
String lname;
String number;
String pattern = "^\\(?(\\d{3})?\\)?[- ]?(\\d{3})[- ](\\d{4})$";
while (fname.length() > 8 || fname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
fname = stdin.nextLine();
}
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname;
System.out.print("Enter last name: ");
lname = stdin.nextLine();
while (lname.length() > 8 || lname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
lname = stdin.nextLine();
}
contactList[num_entries].lname = lname;
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
break;
} else {
return;
}
}
}
contactList[num_entries].number = number;
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine();
num_entries++;
System.out.println();
}
public static void listAllContacts() {
for(Entry e : contactList) {
if(e != null)
displayContact(e);
else
break;
}
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index1(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].lname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index2(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].number.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t");
System.out.println("--"+ contact.lname+"\t");
System.out.println("--"+ contact.number+"\t");
System.out.println("--"+ contact.note);
System.out.println("");
}
public static void sortList1() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].fname.compareToIgnoreCase(contactList[i].fname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void sortList2() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].lname.compareToIgnoreCase(contactList[i].lname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(
contactList[i].fname + "\t" +
contactList[i].lname + "\t" +
contactList[i].number + "\t" +
contactList[i].note);
}
}
public static void removeEntry1(String number) {
Entry[] newcontactList = new Entry[contactList.length];
int i = 0;
for(Entry e : contactList) {
if(e == null) break; // if an entry is null then break the loop
if(e.number.equals(number)) // if the given number matches the current number
continue; // then skip
newcontactList[i++] = e;
}
num_entries--; // decrease the number of entries by 1;
contactList = newcontactList;
}
public static void sortListByPhoneNumber() {
int i;
Entry temp;
for (int j = 0; j < num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].number.compareToIgnoreCase(contactList[i].number) > 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}
listAllContacts();
}
}
The problem is that while you are looping through your contactList in for (Entry e : contactList) you are not checking the whole list!
E.g. if in the first cycle e.number doesn't equal the new number it goes to else statement and breaks the loop, then it goes and calls contactList[num_entries].number = number; saving potentially the already existing number;
To fix your code with minimum changes - just remove the else{ break;}
If you want a safer and more performant solution, use HashSet data structure for your contactList or TreeSet if you want it to be sorted - it will make sure that you will never have a duplicate entry, you can use Set.contains(number) to check if the entry already exists, and additionally HashSet will improve the complexity of entry lookups to O(1), TreeSet slightly worse O(logn) - either better then looping through the whole array which is O(n).
One way you can do that by using a boolean
boolean isPresent = false;
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
isPresent = true;
break;
}
}
Now check if the variable changed or not and do the entry
if (!isPresent) {
contactList[num_entries].number = number;
//rest of code
}
In Java 8 you could use optional
Optional<String> presentPh = Arrays.stream(contactList).filter(e -> e.number.equals(number)).findAny();
Now check if you find anything in filter
if (!presentPh.isPresent()) {
contactList[num_entries].number = number;
//rest of code
}
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()
Trying to fill an array using getter, the problem the array is full with the same number and if the value change in the second input the hole array changes again :
public class Payment {
Scanner kb = new Scanner(System.in);
private int operationNum = 0;
private int subOperationNum = 0;
private double reMoney = 0;
public int getOperationNum() {
return operationNum;
}
public int getSubOperationNum() {
return subOperationNum;
}
public double getReMoney() {
return reMoney;
}
public void setOperationNum(int operationNum) {
this.operationNum = operationNum;
}
public void setSubOperationNum(int subOperationNum) {
this.subOperationNum = subOperationNum;
}
public void setReMoney(double reMoney) {
this.reMoney = reMoney;
}
public void operationsLoop() {
double [] a = new double[17];
do {
System.out.println("\n1- Cash");
System.out.println("2- Car");
System.out.println("3- Clothing");
System.out.println("4- Credit Card");
System.out.println("5- Food");
System.out.println("6- Education");
System.out.println("7- Electronics");
System.out.println("8- Groceries");
System.out.println("9- Health & Fitness");
System.out.println("10- Medical");
System.out.println("11- Travel");
System.out.println("12- Utilities");
System.out.println("13- Finish");
System.out.print("\nEnter the number of operation : ");
this.setOperationNum(kb.nextInt());
this.operation2();
this.operation12();
this.collectReMoney();
**for(int i = 0; i<a.length;i++){
a[i] = this.getReMoney();
System.out.print(a[i] + ", ");
}**
} while (operationNum < 13);
}
public void operation2() {
if (this.getOperationNum() == 2) {
System.out.println("\t1- Gas");
System.out.println("\t2- Repair");
System.out.println("\t3- Monthly Payment");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void operation12() {
if (this.getOperationNum() == 12) {
System.out.println("\t1- Electricity");
System.out.println("\t2- Gas");
System.out.println("\t3- Telephone");
System.out.println("\t4- Water");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void collectReMoney() {
if (this.getOperationNum() == 1) {
System.out.print("Withdraw = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 4 || (this.getOperationNum() == 2 && this.getSubOperationNum() == 3)) {
System.out.print("Payment = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 9 || this.getOperationNum() == 10) {
System.out.print("Pay = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() != 13) {
System.out.print("Spend = ");
this.setReMoney(kb.nextDouble());
}
}
and if I add to the array loop "this.setReMoney(0);" only the first value change
when the user enter a value i want to insert it in the array according to the operation number and the rest values of the other operations should be zero
In the for loop you are assigning the same number to each of the elements of the array, to avoid that you should take the assigning operation outside the for loop:
a[operationNum - 1] = this.getReMoney();
for(int i = 0; i<a.length;i++){
System.out.print(a[i] + ", ");
}
Also, make sure that you check for ArrayIndexOutOfBoundsException in the case the user selects an option number grater than the size of the array.
I am trying to code a simple program in which the user can view and update a list of NBA player's racing for the MVP Trophy. However I have failed in the past to code a program in which can loop for however long the user decides to. I want the program to have the options 1. Go Back & 2. Exit but I cannot figure out how to loop it. Here is my Rank.java & AdminAccount.java. Hope it is not confusing to understand, thank you for reading.
import java.util.Scanner;
public class Rank {
String player[] = { "Stephen Curry", "Russel Westbrook", "Kevind Durant", "LeBron James", "Kawhi Leonard" };
Scanner rankInput = new Scanner(System.in);
Scanner playerInput = new Scanner(System.in);
int rank;
String playerUpdate;
public void Rank() {
System.out.println("Rank\tPlayer");
for (int counter = 0; counter < player.length; counter++) {
System.out.println(counter + 1 + "\t" + player[counter]);
}
}
public void updateRank() {
System.out.print("Select rank to update: ");
rank = rankInput.nextInt();
if (rank == 1) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[0] = playerUpdate;
} else if (rank == 2) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[1] = playerUpdate;
} else if (rank == 3) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[2] = playerUpdate;
} else if (rank == 4) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[3] = playerUpdate;
} else if (rank == 5) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[4] = playerUpdate;
}
}
}
import java.util.Scanner;
public class AdminAccount {
public static void main(String[] args) {
Rank rank = new Rank();
Scanner adminInput = new Scanner(System.in);
Scanner exitInput = new Scanner(System.in);
boolean keepRunning = true;
// menu variables
int menuOption;
int exitOption;
while (keepRunning) {
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if (menuOption == 1) {
rank.Rank();
} else if (menuOption == 2) {
rank.updateRank();
}
}
}
}
Just add an "exit" option to your loop:
while(keepRunning){
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update 3.Exit\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if(menuOption == 1)
{
rank.Rank();
}
else if(menuOption == 2)
{
rank.updateRank();
}
else
{
keepRunning = false;
}
}
This a sample code using arrays
This Program Uses Do.... While Loop to Loop over a whole program when there is a user prompt.
package doWhileLoop;
import java.util.Scanner;
public class doWhileLoop {
public static void main(String[] args) {
//this is a program to prompt a user to continue or pass using the do while loop
String programCounter;
do {
int sum=0;
int list[] = new int[3];
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers to be added: ");
for (int i = 0; i < 3; i++) {
list[i] = in.nextInt();
sum+= list[i];
}
System.out.println("sum = "+ sum);
System.out.println("Enter Yes to continue or No to exit........");
programCounter = in.next();
}
while (programCounter.equals("yes"));
}
}
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.