使用JOptionPane生成随机数并对奇数和偶数进行排序

时间:2015-09-15 03:29:06

标签: java joptionpane

我的第一个问题。我的任务是生成1到10次,20次之间的随机数。在那之后,我应该以某种方式将数字写入两个分开的字符串中,用于奇数和偶数。我们还应该计算每组数字的总数。这是我到目前为止,我需要有关如何显示分隔数字的帮助。我也想使用JOptionPane,但是感谢任何帮助!

package lab5arudy;

import javax.swing.JOptionPane;

public class Lab5ARudy
{

public static void main(String[] args) 
{
   int randomNumber = 0;
   int evenNumbers = 0;
   int oddNumbers = 0;  

   String evenNums;
   String oddNums;


 for (int i = 0; i < 20; i++)
   {
       randomNumber = 1 + (int) (Math.random() * 10);

        if (randomNumber % 2 ==0)
               {                 
                  evenNumbers++;               
               }
            else
                oddNumbers++;       

    }


          JOptionPane.showMessageDialog(null,"Even Numbers: " + evenNumbers);
          JOptionPane.showMessageDialog(null,"Even Numbers: " + oddNumbers );


      }

}        

2 个答案:

答案 0 :(得分:1)

听起来好像你只需要将所有随机数添加到列表中,以便以后可以打印它们。如下所示:

Random rand = new Random();
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
for (int i = 0; i < 20; i++) {
    int next = rand.nextInt(10) + 1;
    if (next % 2 == 0)
        evens.add(next);
    else
        odds.add(next);
}
showMessageDialog("Even :" + evens + " (" + evens.size() + ")");
showMessageDialog("Odds :" + odds + " (" + odds.size() + ")");

答案 1 :(得分:0)

你可以这样做。

public static void main(String[] args) {

    int randomNumber;

    int evenNumbers = 0;
    int oddNumbers = 0;

    String evenNums = "";//initialize empty strings
    String oddNums = "";//initialize empty strings

    for (int i = 0; i < 20; i++) {
        randomNumber = 1 + (int) (Math.random() * 10);
        if (randomNumber % 2 == 0) {
            evenNumbers++;
            if (evenNums.equals("")) {//if the evenNums is empty, append the number
                evenNums = evenNums + randomNumber;
            } else {
                evenNums = evenNums + "," + randomNumber;//if the evenNums is not empty, append the number with a , in between
            }
        } else {
            oddNumbers++;
            if (oddNums.equals("")) {
                oddNums = oddNums + randomNumber;//if the oddNums is empty, append the number
            } else {
                oddNums = oddNums + "," + randomNumber;//if the oddNums is not empty, append the number with a , in between
            }
        }
    }
    JOptionPane.showMessageDialog(null, "Even Numbers: " + evenNumbers+"\n"+evenNums);//Show the even numbers
    JOptionPane.showMessageDialog(null, "Odd Numbers: " + oddNumbers+"\n"+oddNums);//Show the odd numbers
}