我怎样才能添加这个随机整数?

时间:2015-10-27 14:40:46

标签: java

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

我想要做的就是获得总和。例如: 5 4 3 2 1 = 15就像这样。

2 个答案:

答案 0 :(得分:1)

只需将变量sum初始化为0,然后将value添加到其中:

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

答案 1 :(得分:0)

真的不清楚你要做什么,或者你的问题在这里。如果我能猜到,那就是这行代码:

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

您是否只想在此处获取随机整数?你可以用不同的方式做到这一点:

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

您可以在此处查看更详细的说明:How do I generate random integers within a specific range in Java?