2015-10-27 3 views
-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); 
    } 
} 

что я хочу сделать, это получить сумму. Например: 5 4 3 2 1 = 15 просто так.Как добавить эти случайные целые числа?

+0

Как добавить номера? num1 + num2. – csmckelvey

ответ

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

Смежные вопросы