James B James B - 4 years ago 137
Java Question

For loop printing twice sometimes

In my convertEuro method the for loop is causing the output to be printed twice, but only sometimes. What I mean is this is what gets displayed:

Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13
Converting values to Euros.
£4.00 >>> €5.45
£123.44 >>> €168.13


During testing it seems to do this maybe 2 times out of 10, and I can't figure out why. Code below if someone can please help:

import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Conversion {

public void mainMenu(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {

int menuChoice;

System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");

menuChoice = scan.nextInt();

switch (menuChoice) {
case 1:

enterValues(scan, values, twoDecimal);

case 2:

scan.nextLine();
convertEuro(scan, values, twoDecimal);

}

}

public void enterValues(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {
double value = 0;

do {
System.out.print("Enter value. Enter -1 to stop: £");



while (!scan.hasNextDouble()) {
System.out.print("Please enter a double (£xx.xx): £");
scan.nextLine(); //Consumes \n
scan.next();
}

value = scan.nextDouble();

if (value != -1) {
values.add(value);
System.out.println("Value entered.");
}

}
while (value != -1);


System.out.println("Returning to main menu. ");
mainMenu(scan, values, twoDecimal);

}

public void convertEuro(Scanner scan, ArrayList<Double> values, DecimalFormat twoDecimal) {

System.out.println("Converting values to Euros.");

for (int i = 0; i < values.size(); i++) {
System.out.println("£" + twoDecimal.format(values.get(i)) + " >>> " + "\u20ac" + twoDecimal.format(values.get(i) * 1.362));
}
}

public static void main(String[] args) {

Conversion conv = new Conversion();
Scanner scan = new Scanner(System.in);
ArrayList<Double> values = new ArrayList<Double>();
DecimalFormat twoDecimal = new DecimalFormat("0.00");

conv.mainMenu(scan, values, twoDecimal);

scan.close();

}

}

Answer Source

You need to add a break; statement:

case 1:
    enterValues(scan, values, twoDecimal);
    break;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download