[英]How can i add this random integer numbers?
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 就像这样。
只需将变量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 );
}
}
真的不清楚你要做什么,或者你的问题是什么。 如果我能猜到,这是关于这行代码:
value = 1 + ( int ) ( Math.random() * 6 );
你只是想在这里得到一个随机整数吗? 你可以用不同的方式做到这一点:
Random rand;
int randomNum = rand.nextInt((max - min) + 1) + min;
您可以在这里看到更详细的解释: 如何在 Java 中生成特定范围内的随机整数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.