How to time an activity out after a certain timeframe? - android

I want to create an application in which the user has 90 seconds in order to complete a certain number of sums.
I am unsure how to stop the activity and move to another after the timeframe is up?
Activity code:
/**
* Class holding the activity that has the 10 random sums for the user to answer
* #author Ross
*
*/
public class RandomTest extends Activity implements View.OnClickListener {
// declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String[] question = new String[10];
int correctAnswer[] = new int[10];
int[] results = new int[10];
int score = 0;
int questionNumber = 1;
MediaPlayer correctNoise;
MediaPlayer incorrectNoise;
ImageView imageRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
// set up random
setUpRandom();
// Set text view equal to question in array
text.setText(question[questionNumber - 1]);
// set on click listener for the submit button
submit.setOnClickListener(this);
// updateQuestion
updateQuestion();
}
/**
* Method that initialises variables
*/
public void initialiseVars() {
correctNoise = MediaPlayer.create(RandomTest.this, R.raw.correctnoise);
incorrectNoise = MediaPlayer.create(RandomTest.this, R.raw.incorrectnoise);
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
imageRandom= (ImageView) findViewById(R.id.imageViewRandomTest);
}
/**
* Method that creates the random sum for user to answer
*/
public void setUpRandom() {
// setting up new random
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
// Creating random question String
question[questionNumber - 1] = random1 + " x " + random2 + " = ";
// Creating correct answer to question
correctAnswer[questionNumber - 1] = random1 * random2;
}
/**
* Method that updates question after each click
*/
public void updateQuestion() {
// updating question after each click
setUpRandom();
text.setText(question[questionNumber - 1]);
answer.setText("");
}
public void onClick(View v) {
// sets text view equal to what is entered in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //
// setting the user answer equal to the correct part of results array
results[questionNumber - 1] = a;
// If user answer is equal to correct answer then increase score
if (a == correctAnswer[questionNumber - 1]) {
score++;
correctNoise.start();
imageRandom.setImageResource(R.drawable.thumbsup);
}else{
incorrectNoise.start();
imageRandom.setImageResource(R.drawable.thumbsdown);
}
// if question number is under 10
if (questionNumber < 10) {
// updates question number
questionNumber++;
// called after an answer is given
updateQuestion();
} else {
// Passing values to the results activity
Intent intent = new Intent(this, RandomTestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
intent.putExtra("score", score);
// Start Activity
this.startActivity(intent);
}
}
}

Use the AlarmManager and when it calls use finish();

Related

I'm repeatedly getting the initialized value after using if statement in android studio

I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?

Hey a beginner here

how can i match an iteration variable to the input variable in edit text, i wanted to create the armstrong number
it goes like this
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
tv2.setText(sum);
for (int i = 0; i < 5; i++) {
if (i==1){
(1 == 153)
}
}
}
});
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button check;
private TextView result;
private EditText input_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check =(Button) findViewById(R.id.button_check);
check.setOnClickListener(this);
result =(TextView)findViewById(R.id.result);
input_number =(EditText)findViewById(R.id.input_number);
}
#Override
public void onClick(View v) {
int num = Integer.parseInt(input_number.getText().toString());
int n = num;
int check =0,remainder;
while(num>0){
remainder = num % 10;
check = (int) (check + Math.pow(remainder,3));
num = num/10;
}
if(check == n)
result.setText(n+"is an Armstrong Number");
else
result.setText(n+"is not an Armstrong Number");
}
}
To confirm if user input is an armstrong number, you don't need to iterate. You simply need to compute sum of the cube of individual digits and confirm if it arithmetically equals the value of the figure of the digits when combine.
Your code will thus be refactored like below to solve the problem
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
// convert input text to three fields to one String
String joinedText = "" + one + two + three;
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
// you must setText as String
tv2.setText(Integer.toString(sum));
if(sum == Integer.parseInt(joinedText)){
// This is an armstrong number
}else {
// This is not an armstrong number
}
}
});

use shuffelArray as global variable

We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}

Android :Quiz , how to use drawable value instead on assets

I want to pass value from drawable folder . I know the way how to pass value from draw able but have less knowledge to modify below code . In this code all players value are fetched from "Assets" . and I want to pass from drawable . drawable folder has two value , one is " player" folder and another is background image ,some icons. I am not sure about subfolder in drawable will work or not . If not then how I'll exclude background image , icons. I can pass drawable value using array like player[] ={R.drawable.A, R.drawable.B....} . Still unable to modify this code . I am feeling really helpless :(
public class QuizGame extends Activity {
//String used when logging error messages
private static final String TAG = "QuizGame Activity";
//Instance Variables
private List<String> fileNameList; // player file names
private List<String> quizPlayersList; // names of players in quiz
private String correctAnswer; // current correct answer
private int totalGuesses; // number of guesses
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading of next player
private Animation shakeAnimation; // animation for incorrect answers
private TextView answerTextView;
private TextView questionNumberTextView;
private ImageView faceImageView;
private TableLayout buttonTableLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fileNameList = new ArrayList<String>(); // list of image file names
quizPlayersList = new ArrayList<String>(); // players in quiz
guessRows = 3; // defaulted to one row of choices
random = new Random(); // initialize the random number generator
handler = new Handler(); // used to perform delayed operations
// get references to the GUI components
questionNumberTextView = (TextView) findViewById(R.id.questionNumberTextView);
answerTextView = (TextView) findViewById(R.id.answerTextView);
faceImageView = (ImageView) findViewById(R.id.faceImageView);
buttonTableLayout = (TableLayout) findViewById(R.id.buttonTableLayout);
// set questionNumbers Text
questionNumberTextView.setText(
getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
// load the shake animations used to animate incorrect answers
shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3); // animation repeats 3 times
// start a new quiz
resetQuiz();
} //end onCreate method
// set up and start the next quiz
private void resetQuiz(){
// use the AssetManager to get the player image
// file names for the app
AssetManager assets = getAssets();
fileNameList.clear(); // clear the list
// get list of all player names in this region
String[] paths = null;
try {
paths = assets.list("Players");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Error loading ", e);
}
for(String path : paths)
fileNameList.add(path.replace(".jpg", ""));
correctAnswers = 0; // reset number of correct answers
totalGuesses= 0; // reset number of guesses
quizPlayersList.clear(); // clear prior list of quiz countries
// add 10 random file names to the quiz list
int playerCounter = 1;
int numberOfPlayers = fileNameList.size();
while(playerCounter <= 10){
int randomIndex = random.nextInt(numberOfPlayers);
//get random file name
String fileName = fileNameList.get(randomIndex);
//if region is enabled and hasnt been chosen
if(!quizPlayersList.contains(fileName)){
quizPlayersList.add(fileName);
++playerCounter;
}
}
loadNextPlayer(); //start quiz by loading next player
}
// after user guesses a correct player, load the next one
private void loadNextPlayer(){
//get the filename of the next flag and remove it from the list
String nextImageName = quizPlayersList.remove(0);
correctAnswer = nextImageName; //update correct answer
answerTextView.setText(""); //clear the answerTextView
//display the number of the current question in the quiz
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " +
(correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
//extract the region from the next images name
String region = "Players";
//use AssetManager to load next image from assets folder
AssetManager assets = getAssets(); // get apps Asset Manager
InputStream stream; // used to read in player names
try{
//get an InputStream to the asset representing the next flag
stream = assets.open(region + "/" + nextImageName + ".jpg");
//load the asset as Drawable and display on the flagImageView
Drawable flag = Drawable.createFromStream(stream, nextImageName);
faceImageView.setImageDrawable(flag);
}
catch (IOException e){
Log.e(TAG, "Error loading " + nextImageName, e);
}
//clear prior answer buttons from tablerows
for (int row = 0; row < buttonTableLayout.getChildCount(); row++)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList); //shuffle file names
//put the correct answer at the end of the fileNameList
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
//get a reference to the LayoutInflator Service
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// add 3, 6, or 9 answer Buttons based on the value of guessRows
for (int row = 0; row < guessRows; row++){
TableRow currentTableRow = getTableRow(row);
//place Buttons in currentTableRow
for (int column = 0; column < 3; column++){
//inflate guess_button.xml to create new Button
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
//get player name and set it as newGuessButtons text
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getPlayerName(fileName));
//register answerButton listener to respond to clicks
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
}
}
//randomly replace one Button with the correct answer
int row = random.nextInt(guessRows);
int column = random.nextInt(3);
TableRow randomTableRow = getTableRow(row);
String playerName = getPlayerName(correctAnswer);
((Button) randomTableRow.getChildAt(column)).setText(playerName);
} // end loadNextPlayer method
// return the specified TableRow
private TableRow getTableRow(int row){
return (TableRow) buttonTableLayout.getChildAt(row);
}
// parses the player file name and returns the player name
private String getPlayerName(String name){
return name.substring(name.indexOf('-') + 1).replace('-', ' ');
}
// method submitGuess called when user selects an answer
private void submitGuess (Button guessButton){
String guess = guessButton.getText().toString();
String answer = getPlayerName(correctAnswer);
++totalGuesses; //increment the number of guesses made
if (guess.equals(answer)){
++correctAnswers; // increment number of correct answers
//display Correct answer in answerTextView
answerTextView.setText(answer + "!" );
answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));
disableButtons(); //disable all answer Buttons
// if user has guessed 10 correct players
if (correctAnswers == 10){
//create new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reset_quiz);
//set the AlertDialogs message to display the game results
builder.setMessage(String.format("%d %s, %.02f%% %s", totalGuesses,
getResources().getString(R.string.guesses),
(1000 / (double) totalGuesses),
getResources().getString(R.string.correct)));
builder.setCancelable(false);
//add reset quiz button
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
resetQuiz();
} // end onClick
} // end anonymous inner class
); //end call to setPositiveButton
// create AlertDialog from the Builder
AlertDialog resetDialog = builder.create();
resetDialog.show();
} // end if
else // answer is correct but game isnt over
{
//load the next flag after a one second delay
handler.postDelayed(
new Runnable()
{
#Override
public void run(){
loadNextPlayer();
}
}, 1000); // 1000 milliseconds for 1 second delay
} // end else
} // end if
else // answer was incorrect
{
//play the animation
faceImageView.startAnimation(shakeAnimation);
//display "Incorrect" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false); // disable the incorrect answer
}
} // end submitGuess method
// method to disable all answer Buttons
private void disableButtons(){
for (int row = 0; row < buttonTableLayout.getChildCount(); row++){
TableRow tablerow = (TableRow) buttonTableLayout.getChildAt(row);
for(int i = 0; i < tablerow.getChildCount(); i++){
tablerow.getChildAt(i).setEnabled(false);
}
}
}
// create constants for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
// called when the user accesses the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
// add options to the menu
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
return true; // display the menu
}
// called when the user selects an option from the menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch the menu id of the user selected option
switch (item.getItemId())
{
case CHOICES_MENU_ID:
//create a list of the possible number of answer choices
final String[] possibleChoices = getResources().getStringArray(R.array.guessesList);
//create an AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder = new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
//add possibleChoices items to the Dialog and set the
// behavior when one of the items is clicked
choicesBuilder.setItems(R.array.guessesList,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// update guessRows to reflect user choice
guessRows = Integer.parseInt(possibleChoices[item].toString()) / 3;
resetQuiz();
}
});
// create AlertDialog from the Builder
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show();
break;
} // end switch
return super.onOptionsItemSelected(item);
}// end method onOptionsItemSelected

How to Generate Single Random value without Duplicate?

I am doing quize app. In this app questions wont be generate duplicates. so I am using code like int value=random.nextInt(10-1)+1.When i submit the answer random number will generate newly so generating duplicates.How can i compare previous random value with new random values every time ?
Generate from 1 to 10 and store in a list
Shuffle the list of generated numbers
Keep removing from the list
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(i)
}
Collections.shuffle(list);
int value= list.remove(0);
.......
value= list.remove(0);
and so on...
Check this also : Java - generate Random range of specific numbers without duplication of those numbers - how to?
Also storing in a HashMap and checking is a smart way like the other answer says. But this can cause a lot more clashes, since everytime you try to add a duplicate to the HashMap you fail and you have to generate a new one again. But generating all at once and shuffling doesnt cause this. But since the input set is small(10) this collision might not happen too much(depending on the randomness, or maybe it happens too much?) and the O(1) access to the map elements for comparison will help.
Store value in a hashmap and then check if it's already there. If there reroll.
Here is code which i was using at my project. Full source code is
here
package com.banglardin.test_code;
import android.app.*;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.banglardin.test_code.*;
import java.util.*;
public class MainActivity extends Activity {
protected SharedPreferences preference;
protected Questions questionObject;
protected TextView textView;
protected Button buttonView, cleanButton;
protected ArrayList<String> ques_array;
protected final String KEY="Key124";
protected int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//intilized Question and preference
questionObject = new Questions();
preference = getSharedPreferences(KEY,Context.MODE_WORLD_WRITEABLE);
// get array from question object
try{
ques_array= questionObject.getQestions(getApplicationContext());
}catch(Exception e){
e.printStackTrace();
}
// intilized views
textView = (TextView)findViewById (R.id.question);
buttonView = (Button) findViewById (R.id.button);
cleanButton = (Button) findViewById (R.id.button_clean);
textView.setTextSize(18.33f);
buttonView.setTextSize(18.00f);
cleanButton.setTextSize(18.00f);
// set onclickListener on button view
buttonView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int set = 0;
if(i < 6){
while(set == 0){
String history = getString(KEY); // <0>
Random r = new Random();
int id = r.nextInt(ques_array.size());
String s_id= "<"+ String.valueOf(id) + ">"; // ex : <0>
if( !history.contains(s_id)){
textView.setText(ques_array.get(id));
setString(KEY, (history + s_id)); // ex : <0> + <3> = <0><3>;
set = 67;
i++;
}
}
}
else if(i>=6){
textView.setText(getResources().getString(R.string.e2));
Toast.makeText(MainActivity.this,"Questions are not available any more",2).show();
}
}
}
);
// set onclickListener on button view
cleanButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
setString(KEY, "<-0>");
}
}
);
}
#Override
public void onBackPressed(){
if(preference != null){
setString(KEY, ("<-0>"));
finish();
}
super.onBackPressed();
}
/** Get String value from preference */
private String getString(String KEY){
if(preference != null){
return preference.getString(KEY,"<-33>");
}
else{
return null;
}
}
/** Put String value to preference */
private void setString(String KEY, String value){
if(preference != null){
SharedPreferences.Editor edit = preference.edit();
edit.putString(KEY, value);
edit.commit();
}
}
/** Class that gives us all questions */
class Questions{
protected ArrayList<String> data;
public ArrayList<String> getQestions(Context c) throws Exception{
data = new ArrayList<String>();
Resources res= c.getResources();
String qes[] ={
res.getString(R.string.q1) , //0
res.getString(R.string.q2) , //1
res.getString(R.string.q3) , //2
res.getString(R.string.q4) , //3
res.getString(R.string.q5) , //4
res.getString(R.string.q6) , //5
res.getString(R.string.q7) , //6
};
// add all the strings one by one
for(String i : qes){
data.add(i);
}
return data;
}
}
}
use 'HashSet' class in the main property of this class is they contain set of different values mean no value is repeated in it......
so u can generate random no. and add it in set like this
Random r = new Random();
int i = r.nextInt(100);
HashSet<int> s = new HashSet<int>();
s.add(i);
generat random number and add it inti hashset and use it....
an in nextInt parameter have to give maximum no. range...
example code as follows:
Random r = new Random();
//declare a hash set
HashSet set = new HashSet();
for(int i=0;i<50;i++)
{
set.add(r.nextInt(100));
}
// create an iterator
Iterator iterator = set.iterator();
// check values
while (iterator.hasNext()){
System.out.println("Value: "+iterator.next() + " ");
}

Categories

Resources