-4
import javax.swing.JOptionPane;

public class RandomIntegers {

    public static void main( String args[] ) {
        int value;
        String output = "";
        // loop 20 times
        for ( int counter = 1; counter <= 20; counter++ ) {
            // pick random integer between 1 and 6    
            value = 1 + ( int ) ( Math.random() * 6 );
            output += value + "  ";  // append value to output
            // if counter divisible by 5, append newline to String output
            if ( counter % 5 == 0 )
                output += "\n";
        }
        JOptionPane.showMessageDialog( null, output, "20 Random Numbers from 1 to 6",JOptionPane.INFORMATION_MESSAGE );
        System.exit( 0 );
    }
}

what i want to do is to get the sum .for example : 5 4 3 2 1 = 15 just like this.

DJay
  • 7
  • 2

2 Answers2

1

Simply initialize a variable sum to 0, then add value to it:

import javax.swing.JOptionPane;

public class RandomIntegers {

    public static void main( String args[] ) {
        int value;
        String output = "";
        int sum = 0; 
        // loop 20 times
        for ( int counter = 1; counter <= 20; counter++ ) {
            // pick random integer between 1 and 6
            value = 1 + ( int ) ( Math.random() * 6 );
            sum += value;            // Simply add value to sum
            output += value + "  ";  // append value to output
            // if counter divisible by 5, append newline to String output
            if ( counter % 5 == 0 )
                output += "\n";
        }
        JOptionPane.showMessageDialog( null, output, "20 Random Numbers from 1 to 6",JOptionPane.INFORMATION_MESSAGE );
        JOptionPane.showMessageDialog( null, sum, "Total:",JOptionPane.INFORMATION_MESSAGE );
        System.exit( 0 );
    }
}
jh314
  • 27,144
  • 16
  • 62
  • 82
0

Really not clear on what you are trying to do, or what your question is here. If I can guess, it's about this line of code:

value = 1 + ( int ) ( Math.random() * 6 );

Are you just trying to get a random integer here? You can do that a different way:

Random rand;
int randomNum = rand.nextInt((max - min) + 1) + min;

You can see a more detailed explanation here: How do I generate random integers within a specific range in Java?

Community
  • 1
  • 1
DanGordon
  • 671
  • 3
  • 8
  • 26