Search code examples
javaloopsinputswitch-statementjoptionpane

Trying to generate numbers in a range and add the number which was generated to a counter to display as an output


I'm generating random numbers in the range 1 to 7 and assigned 1 to A, 2 to B .... 7 to G. When the random number generates I want to add that number onto a counter till the loop finishes and then output how many numbers of which letter were generated. What I'm trying to achieve when I enter say: 10. I should get the output: Count is as follows:

A: 1

B: 3

C: 1

D: 2

E: 2

F: 1

G: 0

If you count the numbers that were generated is adds up to 10 which was the input, but when I enter say, 10, I get:

A: 3

B: 4

C: 5

D: 5

E: 7

F: 8

G: 11

import javax.swing.JOptionPane;
public class sheet10t3
{
    public static void main(String[] args)
    {
        String menu = "How many random notes would you like?\n(input must be in the range 10 to 50)?", results = "";
        int input = Integer.parseInt(JOptionPane.showInputDialog(null,menu));
        int aNumber, countA = 0, countB = 0, countC = 0, countD = 0, countE = 0, countF = 0, countG = 0;
        if(input < 1 || input > 50)
            results = "Please enter a valid input in the range 1 to 50.";
        else
        {
            for(int i = 0; i <= input; i++)
            {
                aNumber = (int) (Math.random() * 7 + 1);
                switch(aNumber)
                {
                    case 1: countA++;
                    case 2: countB++;
                    case 3: countC++;
                    case 4: countD++;
                    case 5: countE++;
                    case 6: countF++;
                    case 7: countG++;
                }
            }
            results = "Count of each note is as follows:";
            results += "\nA: " + countA;
            results += "\nB: " + countB;
            results += "\nC: " + countC;
            results += "\nD: " + countD;
            results += "\nE: " + countE;
            results += "\nF: " + countF;
            results += "\nG: " + countG;
        }
        JOptionPane.showMessageDialog(null,results);
    }
}

Solution

  • case 1: countA++;
    break;
    case 2: countB++;
    break;
    case 3: countC++;
    break;
    case 4: countD++;
    break;
    case 5: countE++;
    break;
    case 6: countF++;
    break;
    case 7: countG++;
    break;
    

    Solves it