在Android中显示未重复的随机数

时间:2014-11-17 08:07:56

标签: android

我使用以下程序打印出4组未重复的随机数, 每组包含7个数字,范围从0到30.打印 在Java中按预期进行。但是,当在Android应用程序中使用时, 只打印一行7个数字而不是4行。

任何人都可以告诉我为什么Java中打印的结果不同 从Android中的那个。如何在Android中修改代码以获得结果 和Java一样吗?

IN JAVA    
public static void main(String[] args) {    
final int requiredNum = 7;     
final int range= 30;     
final int inputGroupNum = 4; 

 Random random = new Random();
 enter code herefor (int i=1; i<=inputGroupNum; i++) {
 Set set = new HashSet<Integer>(requiredNum);
 while(set.size()< requiredNum) {
 while (set.add(random.nextInt(range)) != true);
}
assert set.size() == requiredNum;
String result ="";
result += set + "\n";
System.out.print(result);
    }
}

IN ADROID
calBtn.setOnClickListener(new OnClickListener() {     
 public void onClick (View view) {     
 final int requiredNum = 7;     
 final int range= 30;     
 final int inputGroupNum = 4;     

 Random random = new Random();
 for (int i=1; i<=inputGroupNum; i++) {
 Set set = new HashSet<Integer>(requiredNum);
 while(set.size()< requiredNum) {
while (set.add(random.nextInt(range)) != true);
}
assert set.size() == requiredNum;
String result ="";
result += set + "\n";
displayTxt.setText(result);    
 }         
}         
});        


Example of print-out in Java                     
[16, 3, 6, 7, 8, 9, 11]                                      
[2, 18, 24, 9, 26, 27, 11]    
[17, 4, 6, 8, 25, 11, 13]    
[0, 1, 2, 21, 24, 9, 28]

Example of display in Android    
[8, 27, 18, 4, 20, 28, 7]    

1 个答案:

答案 0 :(得分:0)

我想你应该试试这个:

calBtn.setOnClickListener(new OnClickListener() {     
 public void onClick (View view) {     
 String result ="";
 final int requiredNum = 7;     
 final int range= 30;     
 final int inputGroupNum = 4;     

 Random random = new Random();
 for (int i=1; i<=inputGroupNum; i++) {
 Set set = new HashSet<Integer>(requiredNum);
 while(set.size()< requiredNum) {
while (set.add(random.nextInt(range)) != true);
}
assert set.size() == requiredNum;
result += set + "\n";
displayTxt.setText(result);    
 }         
}         
});