Iterate through list of objects & methods using for loop - java

The entirety of the code can be found at the bottom of this post, but the only part that really concerns me is,
for(zed = 0; zed<photoes.size(); zed++) {
totesPrice += photoes<zed>.getCost();
totesSize += photoes<zed>.getMegabytes();
totesSpeed = photoes<zed>.getSpeed();
}
Ideally the totesPrice, totesSize, and totesSpeed would be the sum of the get methods for the objects stored in the photoes list array.
// Import classes for class
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class DigitalMain
{
public static void main(String args[])
{
String cont = "Y";
String heightString,width,bitpsString = "";
String widthString = "";
int zed;
double bitps,pHS,pWS = 0.0;
double totesSpeed = 0.0;
double totesPrice = 0.0;
double totesSize = 0.0;
DecimalFormat wholeDigits = new DecimalFormat("0");
DecimalFormat dec = new DecimalFormat("0.00");
List<DigitalPhoto> photoes = new ArrayList<DigitalPhoto>();
do
{
DigitalPhoto photo = new DigitalPhoto();
heightString = JOptionPane.showInputDialog("Please enter height");
pHS = Double.parseDouble(heightString);
photo.setHeight(pHS);
widthString = JOptionPane.showInputDialog("Please enter width");
pWS = Double.parseDouble(widthString);
photo.setWidth(pWS);
JOptionPane.showMessageDialog(null, "Height: " + photo.getHeight() + "\nWidth: " + photo.getWidth() + "\nResolution: " + photo.getResolution() + " DPI\nCompression Ratio: " + photo.getCompression() + "\nRequired Storage: " + dec.format(photo.getKilo()) + " Kilobytes.\nPrice of Scanned Photo: $" + dec.format(photo.getCost()) + " dollars.");
do
{
bitpsString = JOptionPane.showInputDialog("Please enter your internet connection speed in BITS not BYTES please.");
bitps = Double.parseDouble(bitpsString);
} while (bitps < 0 && bitps > 99999999);
photo.setSpeed(bitps);
for(zed = 0; zed<photoes.size(); zed++) {
totesPrice += photoes<zed>.getCost();
totesSize += photoes<zed>.getMegabytes();
totesSpeed = photoes<zed>.getSpeed();
}
cont = JOptionPane.showInputDialog("\nType \'Y\' to try again or anything but \'Y\' to use values.");
photoes.add(photo);
} while (cont.equalsIgnoreCase("Y"));
double seconds = transferTime(totesSize, totesSpeed);
double minutes = seconds / 60;
double realsec = seconds % 60;
JOptionPane.showMessageDialog(null, "You will be paying: " + totesPrice + "\nRequired Storage is: " + totesSize + "Required time for transfer is: " + wholeDigits.format(minutes) + " minutes, and " + wholeDigits.format(realsec) + " seconds.");
}
public static double transferTime(double totalStorage, double netSpeed) {
double bits, seconds;
bits = (totalStorage * 8);
seconds = (bits / netSpeed);
return seconds;
};
}

I think u have to your generics.. for:each
u can try this ...
for (DigitalPhoto digitalPhoto : photoes) {
totesPrice += digitalPhoto.getCost();
totesSize += digitalPhoto.getMegabytes();
totesSpeed = digitalPhoto.getSpeed();
}

for(zed = 0; zed<photoes.size(); zed++)
{
totesPrice += photoes.get(zed).getCost();
totesSize += photoes.get(zed).getMegabytes();
totesSpeed = photoes.get(zed).getSpeed();
}
Try this.

You could use an Iterator instead :
Iterator it = photoes.iterator();
while(it.hasNext())
{
DigitalPhoto temp = it.next();
totesPrice += temp.getCost();
totesSize += temp.getMegabytes();
totesSpeed = temp.getSpeed();
}

Related

Why is my change calculator not working for coins?

I'm trying to make a program that calculates tax and what change needs to be given back, but for some reason, it doesn't tell me what coins to give back. The code tells me which bills I would need to give back, but the coins that are in the decimals don't work. I've tried looking all over stack exchange for a solution, but if I'm being honest, I'm not really sure what to even look for in the first place, so I haven't found a solution. I'm also new to Java and text-based coding in general, so any feedback is appreciated!
Here is my code:
import java.util.*;
public class Decisions1 {
static String taskValue = "C1";
public static void main(String[] args) {
//initiates the scanner
Scanner myInput = new Scanner(System.in);
//creates the variables for the total
double total1 = 0;
//asks for the total cost of all goods
System.out.println("Please enter the total cost of all goods. This program will add tax and calculate the change you must give back to the customer.");
total1 = myInput.nextDouble();
//performs calculations for tax
double tax2 = (total1*1.13);
double tax1 = (double) Math.round(tax2 * 100) / 100;
//creates variable for amount paid
double paid1 = 0;
//prints info to the user and asks how much cash they received
System.out.println("You entered $" + total1 + "\n" + "Total with tax = $" + tax1 + "\n" + "Please enter how much cash was paid by the customer. The amount of change owed to the customer will be displayed.");
paid1 = myInput.nextDouble();
//checks if customer has paid enough
if (tax1 > paid1) {
double owed1 = (tax1-paid1);
System.out.println("The customer still owes $" + owed1 + "!");
} else if (tax1 == paid1) { //checks if the customer has given exact change
System.out.println("The customer has paid the exact amount. You don't have to give them any change.");
} else if (tax1 < paid1) {
//starts change calculations
//variables for money units
double oneHundred = 100;
double fifty = 50;
double twenty = 20;
double ten = 10;
double five = 5;
double toonie = 2;
double loonie = 1;
double quarter = 0.25;
double dime = 0.10;
double nickel = 0.05;
double penny = 0.01;
//variable for change owed (rounded to 2 decimal places
double change1 = Math.round((paid1-tax1)*100)/100;
//calculates remainder
double oneHundredMod = (change1 % oneHundred);
//divides and removes decimal places
double oneHundredOwed = (change1 / oneHundred);
String oneHundredOwed1 = String.valueOf((int) oneHundredOwed);
//does the same thing for fifty
double fiftyMod = (oneHundredMod % fifty);
double fiftyOwed = (oneHundredMod / fifty);
String fiftyOwed1 = String.valueOf((int) fiftyOwed);
//twenties
double twentyMod = (fiftyMod % twenty);
double twentyOwed = (fiftyMod / twenty);
String twentyOwed1 = String.valueOf((int) twentyOwed);
//tens
double tenMod = (twentyMod % ten);
double tenOwed = (twentyMod / ten);
String tenOwed1 = String.valueOf((int) tenOwed);
//fives
double fiveMod = (tenMod % five);
double fiveOwed = (tenMod / five);
String fiveOwed1 = String.valueOf((int) fiveOwed);
//toonies
double tooniesMod = (fiveMod % toonie);
double tooniesOwed = (fiveMod / toonie);
String tooniesOwed1 = String.valueOf((int) tooniesOwed);
//loonies
double looniesMod = (tooniesMod % loonie);
double looniesOwed = (tooniesMod / loonie);
String looniesOwed1 = String.valueOf((int) looniesOwed);
//quarters
double quartersMod = (looniesMod % quarter);
double quartersOwed = (looniesMod / quarter);
String quartersOwed1 = String.valueOf((int) quartersOwed);
//dimes
double dimesMod = (quartersMod % dime);
double dimesOwed = (quartersMod / dime);
String dimesOwed1 = String.valueOf((int) dimesOwed);
//nickels
double nickelsMod = (dimesMod % nickel);
double nickelsOwed = (dimesMod / nickel);
String nickelsOwed1 = String.valueOf((int) nickelsOwed);
//and finally, pennies!
double penniesMod = (nickelsMod % penny);
double penniesOwed = (nickelsMod / penny);
String penniesOwed1 = String.valueOf((int) penniesOwed);
System.out.println("TOTAL CHANGE:" + "\n" + "\n" + "$100 Bill(s) = " + oneHundredOwed1 + "\n" + "$50 Bill(s) = " + fiftyOwed1 + "\n" + "$20 Bill(s) = " + twentyOwed1 + "\n" + "$10 Bill(s) = " + tenOwed1 + "\n" + "$5 Bill(s) = " + fiveOwed1 + "\n" + "Toonie(s) = " + tooniesOwed1 + "\n" +"Loonie(s) = " + looniesOwed1 + "\n" + "Quarter(s) = " + quartersOwed1 + "\n" + "Dime(s) = " + dimesOwed1 + "\n" + "Nickel(s) = " + nickelsOwed1 + "\n" + "Pennies = " + penniesOwed1);
}
}//end main
}// end Decisions1

I need help to print out between what prices the largest absolute difference occurred in the program. (I'm nearly finished.)

I can't figure out the right way to update the prices during the if condition. It's probably really simple but I'm having trouble with it. Here is my code.
public class Change {
public static void main(String[] args) {
final int days = 10;
int largeDiff = 0; // largest difference
int price2 = 0;
int day1 = 1;
int day2 = 2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter stock prices:");
int price1 = sc.nextInt();
for (int i = 2; i <= days; i++) {
price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
price1 = price2;
if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
}
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + price1 + " to " + price2);
System.out.println("happened between day " + day1 + " and day " + day2);
}
}
Your problem is the line
System.out.println("from " + price1 + " to " + price2);
because by the end of your loop, price1 and price2 will both be just the last price entered.
What you need to do is when you store values for largeDiff, day1 and day2, you should also store values for the two prices. Then at the end of the loop, print those stored values instead of price1 and price2.
price2 = sc.nextInt();
int diff1 = Math.abs(price1 - price2);
if (diff1 > largeDiff) {
largeDiff = diff1;
day2 = i;
day1 = day2 - 1;
storedPrice1 = price1;
storedPrice2 = price2;
}
price1 = price2;
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + storedPrice1 + " to " + storedPrice2);
I would use an array to store the values
final int price1 = sc.nextInt();
int[] prices = {price1, 0};
int[] days = {day1, 0};
for (int i = day2; i <= days; i++) {
price2 = sc.nextInt();
int newDiff = Math.abs(price1 - price2);
if (newDiff > largeDiff) {
largeDiff = newDiff;
days[1] = i;
prices[1] = price2;
}
}
System.out.println("Largest change of " + largeDiff);
System.out.println("from " + prices[0] + " to " + prices[1]);
System.out.println("happened between day " + days[0] + " and day " + days[1]);
But I don't trust that loop over the days because if you wanted the largest price between all possible date pairs, you want something like
for (int day1 = 0; day1 <= days; day1++) {
// Get day1 price
for (int day2 = 0; days2 <= days; day2++) {
if (day1 == day2) continue; // skip the same day
// Get day2 price
// Get price between days
// Check against largestDiff
// Store diff, day1, day2, and the prices
}
}

Calculating a separate bonus value for a stat from a list of stats given in an array

public static void stats(){
System.out.println("\nName : " +characterName+ " " +characterClass);
System.out.println("Level : " + Level); //Output the value of Level
do {
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[]{"Str", "Dex", "Con", "Int", "Wis", "Cha"};
int amount;
for (int i = 0; i<statValues.length;i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i]+ " : " +statValues[i]);
if (amount == 10 || amount == 11) {
Bonus = 0;
System.out.print(" [ " + Bonus + "]\n");
}
//Bonus value for integers less than 10
else if (amount < 10) {
Bonus = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus + "]\n");
}
//Bonus value for integers greater than 10
else {
Bonus = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus = Bonus + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
}
while (reRoll.equals("yes"));
}
}
This is just a part of a code. Here i need to calculate the bonus for the Con stat using the variable conBonus. Because in the main method i need to calculate the hitpoints and for that the bonus value used is the bonus in conBonus.
Below is the class where the main method is given.
public class Game {
public static void main(String[] args) {
Character.level();
Character.Class();
Character.stats();
int hitPoints;
hitPoints = Character.Level*((int)((Math.random()*Character.hitDice)+1)+Character.conBonus);
System.out.println("HP : [" +hitPoints+ "]");
}
Will passing the bonus amounts to an array work. If so how can i pass it?
Here is how to store Bonus for each category:
First, change Bonus from an int to an array:
static int[] Bonus;
And in main, create a size of 6:
Bonus = new int[6];
Now to calculate hitPoints, use the array (notice that "Con" is array value 2, or the third element of the array: { "Str", "Dex", "Con", "Int", "Wis", "Cha" }
hitPoints = Character.Level * ((int) ((Math.random() * Character.hitDice) + 1) + Character.Bonus[2]);
Here is the new stats method, which uses the new Bonus array:
public static void stats() {
do {
System.out.println("\nName : " + characterName + " " + characterClass);
System.out.println("Level : " + Level); // Output the value of Level
int []statValues = new int[]{Str, Dex, Con, Int, Wis, Cha};
String[] stats = new String[] { "Str", "Dex", "Con", "Int", "Wis", "Cha" };
int amount;
for (int i = 0; i < statValues.length; i++) {
statValues[i] = rollDice();
amount = statValues[i];
System.out.print(stats[i] + " : " + statValues[i]);
if (amount == 10 || amount == 11) {
Bonus[i] = 0;
System.out.print(" [ " + Bonus[i] + "]\n");
}
// Bonus value for integers less than 10
else if (amount < 10) {
Bonus[i] = 0;
bonusCounter = amount;
while (bonusCounter < 10) {
if (bonusCounter % 2 == 1) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[-" + Bonus[i] + "]\n");
}
// Bonus value for integers greater than 10
else {
Bonus[i] = 0;
bonusCounter = 11;
while (bonusCounter <= amount) {
if (bonusCounter % 2 == 0) {
Bonus[i] = Bonus[i] + 1;
}
bonusCounter = bonusCounter + 1;
}
System.out.print("[+" + Bonus[i] + "]\n");
}
}
System.out.println("Type \"yes\" to re-roll or press any key to terminate the program");
reRoll = sc.next();
} while (reRoll.equals("yes"));
}

Array Length Outcome

My problem is probably ridiculously easy and I'm just missing something. My program crashes due to a null value of cell 1 during its first iteration. i troubleshot a bit myself and realized on iteration 1 the array length is 1 then after all other iterations the length is 2. this initial improper length causes a complete crash. Any ideas?
`import java.util.Scanner;
import java.io.*;
/* Takes in all of users personal information, and weather data. Then proceeds to determine status of day + averages of the data values provided, then reports to user*/
public class ClimateSummary
{
public static void main (String [] args) throws FileNotFoundException
{
Scanner sc = new Scanner (new File(args[0]));
String name = sc.nextLine();
String birthCity = sc.next();
String birthState = sc.next();
String loc = sc.next();
int birthDay = sc.nextInt();
String birthMonth = sc.next();
int birthYear = sc.nextInt();
int highTemp = 0;
double avgTemp;
double avgPrecip;
int coldDays = 0;
int hotDays = 0;
int rainyDays = 0;
int niceDays = 0;
int miserableDays = 0;
double totalTemp = 0;
double totalPrecip = 0;
int i = 0;
while(i <= 5)
{
String storage = sc.nextLine();
String[] inputStorage = storage.split(" "); //couldnt find scanf equiv in c for java so using array to store multiple values.
System.out.println(inputStorage[0]);
int tempTemp = Integer.parseInt(inputStorage[0]);
double tempPrecip = Double.parseDouble(inputStorage[1]);
totalTemp = totalTemp + tempTemp;
totalPrecip = totalPrecip + tempPrecip;
if(highTemp < tempTemp)
{
highTemp = tempTemp;
}
if(tempTemp >= 60.0)
{
hotDays++;
}else{
coldDays++;
}
if(tempPrecip > 0.1)
{
rainyDays++;
}
if(tempTemp >= 60.0 || tempTemp <= 80.0 || tempPrecip == 0.0)
{
niceDays++;
}else if(tempTemp < 32.0 || tempTemp > 90.0 || tempPrecip > 2.0)
{
miserableDays++;
}else{
}
i++;
}
avgTemp = totalTemp/5;
avgPrecip = totalPrecip/5;
System.out.println("Name: " + name);
System.out.println("Place of birth: " + birthCity + "," + birthState);
System.out.println("Data collected at: " + loc);
System.out.println("Date of birth: " + birthMonth + " " + birthDay +", " + birthYear);
System.out.println("");
System.out.println("The highest temperature during this tine was " + highTemp + " degrees Farenheit");
System.out.println("The average temperature was " + avgTemp + " degrees Farenheit");
System.out.println("The average amount of precipitation was " + avgPrecip + " inches");
System.out.println("Number of hots days = " + hotDays);
System.out.println("Number of cold days = " + coldDays);
System.out.println("Number of rainy days = " + rainyDays);
System.out.println("Number of nice days = " + niceDays);
System.out.println("Number of miserable days = " + miserableDays);
System.out.println("Goodbye and have a nice day!");
}
Eric Thomas
Columbus
Nebraska
Columbus
18
February
1990
54 0
44 2.2
64 0.06
26 0.5
34 0.02
If your file contains null values then you should handle it separately.... using something like this:
if (name == null) {
//do something
}
else {
// do something else;
}
A good discussion on nulls can be seen here...How to check for null value in java
Also, after splitting a string, you need to check if the array (which is the output) has values at the indices that you are using.
For example:
String name = "A/B/C";
String[] nameArray = name.split("/");
In the above case, nameArray[3] will throw an error.

Unsure about the best loop to use

public static void main(String[] args) {
Scanner keybNum = new Scanner(System.in);
Scanner keybStr = new Scanner(System.in);
boolean yn = false;
//Start of program
System.out.println("Welcome to The Currency Exchange Converter");
System.out.print("Are you an Account Holder (y or n)? ");
String AccHolder = keybStr.next();
boolean blnYN = true;
//validation of y/n answer
while (blnYN) {
if (AccHolder.equalsIgnoreCase("y")) {
yn = true;
blnYN = false;
break;
}//if
else if (AccHolder.equalsIgnoreCase("n")) {
yn = false;
blnYN = false;
break;
}//else if
else {
System.out.println("Invalid value entered. Choose either y/n.");
AccHolder = keybStr.next();
}//else
}//while
//Start of menu choices
System.out.println("Please choose from the following menu.");
System.out.println("\n1: Exchange another currency for Sterling");
System.out.println("2: Buy another currency from us");
System.out.println("0: Exit");
System.out.print("Which option? ");
int MenuChoice = keybNum.nextInt();
//Exchange Variables (First option)
double Euro = 1.37;
double USAD = 1.81;
double JapYen = 190.00;
double Zloty = 5.88;
//Buy Variables (Second Option)
double EuroB = 1.21;
double USADB = 1.61;
double JapYenB = 163.00;
double ZlotyB = 4.89;
//First menu choice screen
if (MenuChoice == 1) {
System.out.println("Which of the following currencies do you wish to exchange into sterling?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
//Exchange amount calculator
System.out.print("Enter the amount you wish to exchange of " + CurChoice + ": ");
double ExcAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = ExcAmount / Euro;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("USD")) {
result = ExcAmount / USAD;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("JPY")) {
result = ExcAmount / JapYen;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else if (CurChoice.equals("PLN")) {
result = ExcAmount / Zloty;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(ExcAmount + " in " + CurChoice + "\t=£" + df.format(result));
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (ExcAmount < 1000) {
commission = result * 0.02;
} else {
commission = result * 0.01;
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t=£" + df.format(commission);
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t=£" + df.format(netPayment));
}//if
//Start of second option
else if (MenuChoice == 2) {
System.out.println("Which of the following currencies do you wish to buy from us?");
System.out.println("Euro - EUR");
System.out.println("USA Dollar - USD");
System.out.println("Japanese Yen - JPY");
System.out.println("Polish Zloty - PLN");
System.out.print("Please enter the three letter currency: ");
//Currency input validation
String CurChoice = "";
boolean isCorrectCurrency = false;
do {
CurChoice = keybStr.next();
isCorrectCurrency = CurChoice.matches("^EUR|USD|JPY|PLN$");
if (isCorrectCurrency) {
System.out.println("");
} else {
System.out.print("Invalid Currency Entered. Please Retry: ");
}
} while (!isCorrectCurrency);
System.out.print("Enter the amount you wish to buy in £ of " + CurChoice + ": £");
double BuyAmount = keybStr.nextInt();
double result = 0.00;
//Selection and calculation of user's input
if (CurChoice.equals("EUR")) {
result = BuyAmount * EuroB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("USD")) {
result = BuyAmount * USADB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("JPY")) {
result = BuyAmount * JapYenB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else if (CurChoice.equals("PLN")) {
result = BuyAmount * ZlotyB;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("£" + BuyAmount + "\t\t= " + df.format(result) + " " + CurChoice);
} else {
System.out.println("");
}
DecimalFormat df = new DecimalFormat("#.##");
double commission = 0;
if (BuyAmount < 1000) {
commission = result * 0.02;
} else if (BuyAmount >= 1000) {
commission = result * 0.01;
} else {
}
String stringToPrint = "";
if (!yn) {
stringToPrint = "Commission\t= " + df.format(commission) + " " + CurChoice;
} else {
stringToPrint = "Commission \t= Not charged";
}
System.out.println(stringToPrint);
double netPayment = result - commission;
System.out.println("Total\t\t= " + df.format(netPayment) + " " + CurChoice);
}//else if
//Action if the user selects 0 to close the system.
else {
System.out.println("Thank you for visiting.");
}//else
}//main
So I'm not sure about the best loop to use on my program. I want the program to repeat if the user inputted either 1 or 2 at the start of the program. The programs a simple currency exchange converter. Any help?
Ideally, you have a program logic according to:
int choice = 0;
while( (choice = readChoice()) != 0 ){
// process according to choice
// ...
}
Wrap the first menu in a static method:
public static int readChoice()
And add the while statement.
(All of your code would benefit from being structured in methods. It's getting unwieldy as you are adding new features. Remember - I have seen an older version)
Consider a do { } while(...); loop. it should be do {...} while (MenuChoice == 1 || MenuChoice == 2); Make sure MenuChoice is always given a value before reaching the while statement. The do while should surround starting from the line //Start of menu choices and to the bottom.
Also, consider a switch case for the MenuChoice

Categories

Resources