Hello friends,
Random number generate without duplicate.
In Android
MainActvity.java
package com.samset.user.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
generateRandom();
}
});
}
public static void generateRandom() {
Random rand = new Random();
Set<Integer> set = new HashSet<Integer>();
while(set.size() < 5) {
set.add(rand.nextInt(9)+2);
}
String numStr = "";
for(Integer n : set) {
numStr += n;
}
int num = Integer.parseInt(numStr);
System.out.print(" Random Number is "+num);
Log.e("TAG"," Random Number is "+num);
}
}
In Java
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 8; i++) {
generateRandom();
}
}
Output:
1: Random Number is 87953
2: Random Number is 810953
3: Random Number is 810932
4: Random Number is 107953
5: Random Number is 410523
Thank you
Random number generate without duplicate.
In Android
MainActvity.java
package com.samset.user.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
generateRandom();
}
});
}
public static void generateRandom() {
Random rand = new Random();
Set<Integer> set = new HashSet<Integer>();
while(set.size() < 5) {
set.add(rand.nextInt(9)+2);
}
String numStr = "";
for(Integer n : set) {
numStr += n;
}
int num = Integer.parseInt(numStr);
System.out.print(" Random Number is "+num);
Log.e("TAG"," Random Number is "+num);
}
}
In Java
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 8; i++) {
generateRandom();
}
}
Output:
1: Random Number is 87953
2: Random Number is 810953
3: Random Number is 810932
4: Random Number is 107953
5: Random Number is 410523
Thank you
No comments:
Post a Comment