How can i load a random image out of 2 ?
I tried this code
final Random rgenerator = new Random();
Integer [] mImageIds =
{
R.drawable.mantrans,
R.drawable.womentrans,
};
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
gBall1 = BitmapFactory.decodeResource(getResources(), q);
but it did not work...
Please help
this is useful to you..
/////*****Random numbers with out repetation*****//////
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3 };
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>(maxNoOfImages);
for (int i = 0; i < maxNoOfImages; i++) {
while(true) {
Integer next = rng.nextInt(maxNoOfImages);
if (!generated.contains(next)) {
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
generated.add(next);
break;
}
}
}
This is kind of a too much for such a simple task. But I haven't really used the Random class. This is an alternative method.
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(R.drawable.mantrans);
ids.add(R.drawable.womentrans);
Collections.shuffle(ids);
gBall1 = BitmapFactory.decodeResource(getResources(), ids.get(0));
You may need to add a bit more id's as getting random in 2 options might not seem much random like pents90 mentioned.
Related
what I will use to prevent the image from appearing again. I want the image won't reapeat appearing but don't know what can I use to do that.
public ImageView imgViewQuestion;
int [] image_list = {
R.drawable.forms,
R.drawable.tags,
R.drawable.tables,
R.drawable.radiobutton,
R.drawable.checkbox,
R.drawable.font,
R.drawable.anchors,
R.drawable.html
};
private void setupList() {
Random random = new Random();
int imageSelected = image_list[random.nextInt(image_list.length)];
imgViewQuestion.setImageResource(imageSelected);
fourinfoassucommon.imageSelected = imageSelected;
correct_answer = getResources().getResourceName(imageSelected);
correct_answer = correct_answer.substring(correct_answer.lastIndexOf("/") + 1);
answer = correct_answer.toCharArray();
fourinfoassucommon.user_submit_answer = new char[answer.length];
suggestSource.clear();
for (char item : answer) {
suggestSource.add(String.valueOf(item));
I'm currently working on a school project (a small android game) and so far I've written a code which generates a random equation 2 seconds after the activity InGame is launched and displays it in a textview. Another 5 seconds later, the second equation is generated and displayed in a different textview. Now the user has to decide if the second equation has a bigger result than the first one by either pressing the button bigger or smaller. If it was correct, the next equation should be displayed and it would go on like this until the user decided wrong.
Here is my code so far:
(Code for the first equation):
// Generate random equation and display it in textview
String[] operationSet = new String[]{"+", "-", "/", "*"};
String equation;
static double doubleAnswer1;
public void start1() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView_first_equation);
TextEquation.setText(equation);
// Evaluate the result of the equation
double doubleAnswer1 = eval(equation);
String stringAnswer = Double.toString(doubleAnswer1);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
}
(Code for second equation (basically same as for first equation except the name of the strings and doubles are different)):
String equation2;
static double doubleAnswer2;
public void start2() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation2 = "";
for (int i = 0; i < numOfOperations; i++) {
equation2 += numbers.get(i);
equation2 += operations.get(i);
}
equation2 += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation2);
// Evaluate the result of the equation
double doubleAnswer2 = eval(equation2);
String stringAnswer = Double.toString(doubleAnswer2);
TextView textAnswer = (TextView)findViewById(R.id.textView_result2);
textAnswer.setText(stringAnswer);
}
And here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
// Display first equation 2 seconds after the activity is launched
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
start1();
}
}, 2000);
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
start2();
}
}, 7000);
// Check if user was right or wrong
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
}
The app launches correctly and it also displays the first and second equation, but when I press one of the button, it tells me in the logcat you are wrong but I decided 100% correct. However if I debug the app, it tells me that doubleAnswer1 and doubleAnswer2 are both = 0. That's why it all ways tells me 'you are wrong'. I don't know how to fix this, maybe I need to store the doubleAnswer1 and doubleAnswer2 somewhere.
I really don't know what to do, so it would really help me if someone has an idea what to do.
If anything is unclear in my question, feel free to ask and I will try to clarify the problem.
Thank you in advance for your help!
I think your problem lies here:
double doubleAnswer1 = eval(equation);
I did a quick internet search and did not find any native function called eval(). Instead you should look into Script Engine Manager for java:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
or exp4j which is shown here:
Executing math equation in Android
Edit:
change the following:
double doubleAnswer1 = eval(equation);
to:
doubleAnswer1 = eval(equation);
Similarly do the same for doubleAnswer2
Hi I have two array values
loncountries[index] = [80.2116001, 80.173399]
latcountries[index] = [13.042699, 13.0409047]
Now I want them in a new Array like
loncountries[index] = [13.042699,80.2116001]
latcountries[index] = [13.0409047,80.173399]
Just the first columns as a new Array. Also I am fetcihg it from Sqlite Database and attaching the code below. Is it possible to do it during fetching from db.
String[] latcountries;
String[] loncountries;
if (cJoin != null) {
int countJoin = cJoin.getCount();
if (countJoin > 0) {
latcountries = new String[countJoin];
loncountries = new String[countJoin];
int index = 0;
cJoin.moveToFirst();
while (!cJoin.isAfterLast()) {
loncountries[index] = cJoin.getString(0);
latcountries[index] = cJoin.getString(1);
index++;
cJoin.moveToNext();
}
}
}
one approach could be to declare a bean-like class,
public class Position {
public String mLat;
public String mLon;
}
and then declare an array of position:
Position[] latLon = new Position[countJoin];
at every iteration then
while (!cJoin.isAfterLast()) {
Position p = new Position();
p.mLat = cJoin.getString(1);
p.mLon = cJoin.getString(0);
latLon[index++] = p;
}
I have Images in drawable and I shuffle these images But I want that R.drawable.a this image come 5 time and this R.drawable.b come 10 time but in my code image come again and again.
My question is that I want that image a R.drawable.a come 5 time after that image R.drawable.a remove from list and other images come on shuffling all images .
But in mean time image a R.drawable.a come n time
public void addNewImageToScreen() {
//array of all drawable id's
int pics[] = { R.drawable.a, R.drawable.b, R.drawable.c, ...etc...};
Random rand = new Random();
int pos = rand.nextInt(pics.length);
addNewImageToScreen(pics[pos]);
}
Can Anybody help me how this is possible?
You need to remove the one you have shown earlier
addNewImageToScreen(pics[pos]);
int arraySize=pics.length;
pics[pos] = pics[--arraySize];
Edit:
or use this logic
ArrayList picsarr=Arrays.asList(pics);
for(int i=0;i<picsarr.size;i++)
{
Collections.shuffle(picsarr);
addNewImageToScreen(picsarr.get[i]);
picsarr.remove(i);
}
Try this code i think it will help you but i am not sure in my case it works fine
Random random = new Random( System.currentTimeMillis() );
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < imageViews.length; i++) {
int v = imageViews[i];
int next = random.nextInt( 15 ) + 1;
if ( !generated.contains( next ) ) {
generated.add( next );
ImageView iv = (ImageView) findViewById( v );
iv.setImageResource( images[next] );
}
else {
i--;
}
}
After some discussion with this fella it seems that this is what he wants:
private ArrayList<Integer> mDrawableIds = new ArrayList<Integer>();
private void populateList() {
mDrawableIds.add(R.drawable.a);
mDrawableIds.add(R.drawable.b);
mDrawableIds.add(R.drawable.c);
}
private int returnImageResource(int buttonClickCount) {
int imageResource = -1;
switch (buttonClickCount) {
case 1:
imageResource = mDrawableIds.get(0);
break;
case 2:
imageResource = mDrawableIds.get((int) (Math.random() * mDrawableIds.size()));
break;
case 3:
imageResource = mDrawableIds.get(1);
break;
// more cases here
case 10:
imageResource = mDrawableIds.get((int) (Math.random() * mDrawableIds.size()));
mDrawableIds.remove(0);
break;
}
return imageResource;
}
I left out some code but this should get you started. What you lacked was an ArrayList which you can remove entries from dynamically.
I am working on a little tiny game, where there is a Attacker and a Defender.
Player Attacker = new Player();
Player Defender = new Player();
class Player {
int armees = 0;
int tarningar = 0;
Dice Dices[];
Player() {
armees = 10;
// if object name is Attacker, tarninger = 3, if defender = 2
Dices= new Dice[tarningar];
for(int i = 0; i < Dices.length; i++) {
Dices[i]=new Dice();
}
}
}
I have commented inside the code above, where i wish to have a if statement to determine how many dices it should have.
If this is not possible to do, another way of doing this maybe?
I also tried to
Attacker.tarningar = 3;
Defender.tarningar = 2;
right under where the object gets defined in main, but it doesn't work, because it has already ran Player() inside class.
(I'm still new to java) Thanks
Maybe you could do:
Player(boolean isAttacker){
armees = 10;
// if object name is Attacker, tarninger = 3, if defender = 2
int diceNum;
if (isAttacker) diceNum = 2;
else diceNum = 3;
Dices= new Dice[diceNum];
for(int i=0;i<Dices.length;i++){
Dices[i]=new Dice();
}
}
Then you will need to tell the player if it is attacking or defending when it is constructed.
Player p = new Player(true); // creates an attacker
You should add a variable determining whether this is an attacker or a defender. Or even better, if they do different things, create subclasses for attacker and defender.
Change your code to this:
Player Attacker = new Player(true);
Player Defender = new Player(false);
class Player {
boolean attacker;
int armees = 0;
int tarningar = 0;
Dice Dices[];
Player(boolean attacker) {
this.attacker = attacker;
armees = 10;
tarninger = attacker ? 3 : 2;
Dices= new Dice[tarningar];
for(int i = 0; i < Dices.length; i++) {
Dices[i] = new Dice();
}
}
}
If you are trying to differentiate based on variable names, it's not possible because that information is removed during compiler optimizations. If the instances are accessible, you could do
if (this == attacker)
{
...
}
or you could introduce a new field to store name
Player attacker = new Player("Attacker");
or perhaps an enum.
Player attacker = new Player(PlayerType.Attacker);