How to Loop a simple program in Java? - java

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

Related

How do you create a continuous loop for a Coin tossing game in Java?

I am having issues trying to make my code loop back and do the program over again until the user asks them to stop by inputting zero. I have tried a while statement but I am not sure if I implemented it correctly since all I got back was errors. I appreciate any and all the help that can be given. I have included my code below.
public class CoinTossing {
public static void main(String[] args) {
//Scanner method
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
Random rand = new Random();
// Simulate the coin tosses.
for (int count = 0; count < number; count++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
return;
}
}
}
Your main method could look something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
//Variables for the count of heads and tails.
while (true) {
int headCount = 0;
int tailCount = 0;
System.out.println("How many coin flips do you want to do?");
int number = input.nextInt();
if (number == 0) { break; }
Random rand = new Random();
// Simulate the coin tosses.
for (int i = 0; i < number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
} else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
}
}
Here, the while loop is entered after the welcome message and will only exit the simulation when the user inputs a 0.
After the user input is retrieved, it will check if the user input 0. If the user inputs 0, it will break the while loop before the program simulates flipping the coin:
if (number == 0) { break; }
Place your code into a while loop with the exception of these two lines:
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Coin Toss Program.");
At the end of the Coin Toss Game the natural order of things would be to ask the User if he/she wants to play again. This allows the User to quit the application rather than being stuck in a continuous loop:
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
The whole application may look something like this:
public class CoinTossing {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
java.util.Random rand = new java.util.Random();
System.out.println("Welcome to the Coin Toss Program");
System.out.println("================================");
System.out.println();
String yn = "y";
while (yn.equalsIgnoreCase("y")) {
int headCount = 0;
int tailCount = 0;
int number = 0;
String num = null;
while (num == null) {
System.out.print("How many coin flips do you want to do? --> ");
num = input.nextLine();
if (!num.matches("\\d+")) {
System.err.println("Invalid Integer Number Supplied ("
+ num + ")! Try Again...");
System.out.println();
num = null;
}
}
number = Integer.valueOf(num);
// Simulate the coin tosses.
for (int i = 1; i <= number; i++) {
if (rand.nextInt(2) == 0) {
tailCount++;
}
else {
headCount++;
}
}
System.out.println("Times head was flipped:" + headCount);
System.out.println("Times tail was flipped:" + tailCount);
System.out.println();
while (yn.equalsIgnoreCase("y")) {
System.out.print("Do you want to play again? (y/n) --> ");
yn = input.nextLine();
if (yn.matches("[yYnN]")) {
System.out.println();
break;
}
else {
System.err.println("Invalid response (" + yn + ")! 'y' or 'n' only!");
System.out.println();
yn = "y";
}
}
}
}
}

Not sure how to do a while loop in this situation

I am writing a program to take the input for a sequence
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
This should be a usable implementation:
public class Menu {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
boolean orderCompleted = false;
while(!orderCompleted) {
printMenu();
String orderString = a.nextLine();
int order = Integer.parseInt(orderString);
int total = 0;
if(order == 1) {
} else if(order == 2) {
} else if(order == 3) {
} else if(order == 4) {
} else if(order == 5) {
}
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
orderString = a.nextLine();
if(orderString.equals("n")){
orderCompleted = true;
}
}
}
private static void printMenu() {
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println("");
System.out.print("Please enter your order selection:");
}
}
I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.
import java.util.Scanner;
public class FibonacciCode {
public static void main(String[] args) {
System.out.println("Enter a number");
int count, number0 = 0, number1 = 1, loop = 0;
Scanner userInput = new Scanner(System.in);
count = userInput.nextInt();
while(loop > count)
{
System.out.print(number0 + ", ");
int sum = number0 + number1;
number0 = number1;
number1 = sum;
loop++;
}
}
}
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input
while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
order = b.nextInt(); // This is inside the block
}
you should use a do while loop instead, like so:
do{
System.out.println("Welcome to Hess Burgers");
System.out.println("1- Cheeseburger.............$7");
System.out.println("2- Barbeque Burger..........$8");
System.out.println("3- Southwestern Burger......$9");
System.out.println("4- Bacon Cheeseburger.......$10");
System.out.println("5- Double Stack Burger......$11");
System.out.println(" ");
System.out.print("Please enter your order selection:");
Scanner a = new Scanner(System.in);
int order = a.nextInt();
int total = 0;
boolean continuePlay = true;
if (order == 1 ) {
} else if (order == 2) {
} else if (order == 3) {
} else if (order == 4) {
} else if (order == 5) {
}
Scanner b = new Scanner(System.in);
System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
} while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

Counting occurrence of attributes inside the objects of a Java Array

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

Java Array Issues with adding in the Array and Sorting alphabetically

I am having some trouble figuring out how to sort the array as well as adding another name to the array. I am relatively new at coding java and I cant seem to figure it out. (The trouble is in choice 4 and enterTVshow() )
Any suggestions on how to approach this?
Thanks
import java.io.*;
import java.util.Arrays;
public class JavaVision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String name[] = new String[48];
public static void main(String[] args) throws IOException {
int choice;
do {
System.out.println(" ");
System.out.println("Java TV Program Menu");
System.out.println("----------------------------");
System.out.println("What would you like to do?");
System.out.println("1. Add a TV Show");
System.out.println("2. Modify a TV Show");
System.out.println("3. Delete a TV Show");
System.out.println("4. Sort TV Shows");
System.out.println("5. Show All TV Shows");
System.out.println("6. Exit");
choice = Integer.valueOf(in.readLine()).intValue();
if(choice ==1) {
enterTVshow();
}
if(choice ==2) {
modTVshow();
}
if(choice ==3) {
deleteTVshow();
}
if (choice ==4) {
Arrays.sort(name);
for (int i = 0; i < name.length; i++) {
}
}
if(choice ==5) {
System.out.println(Arrays.toString(name));
}
}while (choice !=6);
}
private static void deleteTVshow() throws IOException {
String deleteTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("Which TV Show do you want to delete?");
deleteTVshow = in.readLine();
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x;
found = true;
}
}
if (found == false) {
System.out.println("There is no TV Show by that name.");
}
else {
for(i = flag; i <=(x-2); x++) {
name[i] = name[i+1];
}
x = x -1;
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void modTVshow() throws IOException {
String modTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("What is the TV Show you wish to modify?");
modTVshow = in.readLine();
for(i = 0; i<= (x-1); i++) {
if(modTVshow.compareTo(name[i]) == 0) {
flag = i;
found = true;
}
}
if (found == false) {
System.out.print("There is no TV show by that name.");
}
else {
System.out.print("Enter new Name: ");
name[flag] = in.readLine();
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void enterTVshow() throws IOException {
x = 0;
do {
System.out.print("Enter TV Show Name:");
name[x] = in.readLine();
x++;
System.out.print("Adding Show.....");
System.out.println(" ");
System.out.print("Type 'go back' to go back to the menu ");
}while((in.readLine().compareTo("go back")) !=0);
}
}
You are facing problem in sorting because you might have some null value in any of 48 elements of array. to handle this just make your own comparator for sort like below or avoid null value in array.
public class JavaVision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String name[] = new String[48];
public static void main(String[] args) throws IOException {
int choice;
do {
System.out.println(" ");
System.out.println("Java TV Program Menu");
System.out.println("----------------------------");
System.out.println("What would you like to do?");
System.out.println("1. Add a TV Show");
System.out.println("2. Modify a TV Show");
System.out.println("3. Delete a TV Show");
System.out.println("4. Sort TV Shows");
System.out.println("5. Show All TV Shows");
System.out.println("6. Exit");
choice = Integer.valueOf(in.readLine()).intValue();
if(choice ==1) {
enterTVshow();
}
if(choice ==2) {
modTVshow();
}
if(choice ==3) {
deleteTVshow();
}
if (choice ==4) {
sortArray(name);
}
if(choice ==5) {
System.out.println(Arrays.toString(name));
}
}while (choice !=6);
}
private static void deleteTVshow() throws IOException {
String deleteTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("Which TV Show do you want to delete?");
deleteTVshow = in.readLine();
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x;
found = true;
}
}
if (found == false) {
System.out.println("There is no TV Show by that name.");
}
else {
for(i = flag; i <=(x-2); x++) {
name[i] = name[i+1];
}
x = x -1;
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void modTVshow() throws IOException {
String modTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("What is the TV Show you wish to modify?");
modTVshow = in.readLine();
for(i = 0; i<= (x-1); i++) {
if(modTVshow.compareTo(name[i]) == 0) {
flag = i;
found = true;
}
}
if (found == false) {
System.out.print("There is no TV show by that name.");
}
else {
System.out.print("Enter new Name: ");
name[flag] = in.readLine();
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void enterTVshow() throws IOException {
System.out.println();
x = 0;
while(name[x]!=null){
x++;
}
do {
System.out.print("Enter TV Show Name:");
name[x] = in.readLine();
x++;
System.out.print("Adding Show.....");
System.out.println(" ");
System.out.print("Type 'go back' to go back to the menu ");
sortArray(name);
}while((in.readLine().compareTo("go back")) !=0);
}
public static void sortArray(String [] myArray){
Arrays.sort(myArray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}});
}
}
remove the code does not convince me two for
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x; //should not change by flag=i; ?
found = true; // add break; ?
}
}
for rearranging the elements
for(i = flag; i <=(x-2); x++) { //increases why x? should not be i ++? i<=x condition?
name[i] = name[i+1];
}
do not forget that once found an element in the array cut the cycle to avoid delay // break;

Java_Fill an array by getters

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.

Categories

Resources