How to randomly generate random operators in android studio - java

public class MainActivity extends AppCompatActivity {
Button startButton;
ArrayList<Integer> answers=new ArrayList<Integer>();
int LocationOfRightAnswer;
TextView resultTextView;
TextView pointText;
Button button1;
Button button2;
Button button3;
Button button4;
int score=0;
int numberofquestions = 0;
TextView sumText;
TextView timertext;
RelativeLayout game;
Button playAgain;
public void playAgain(View view) {
score = 0;
numberofquestions = 0 ;
timertext.setText("30s");
pointText.setText("0/0");
resultTextView.setText("");
playAgain.setVisibility(View.INVISIBLE);
generateQuestion();
new CountDownTimer(30100,1000) {
#Override
public void onTick(long millisUntilFinished) {
timertext.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
#Override
public void onFinish() {
playAgain.setVisibility(View.VISIBLE);
timertext.setText("0s");
resultTextView.setText("Your Score is " + Integer.toString(score) + "/" + Integer.toString(numberofquestions));
}
}.start();
}
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
sumText.setText(Integer.toString(a) + "+" + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(a + b);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer == a + b) {
incorrectAnswer = random.nextInt(41);
}
answers.add(incorrectAnswer);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAnswer(View view) {
if (view.getTag().toString().equals(Integer.toString(LocationOfRightAnswer))) {
score++;
resultTextView.setText("Correct");
} else {
resultTextView.setText("Wrong!");
}
numberofquestions++;
pointText.setText(Integer.toString(score) + "/" + Integer.toString(numberofquestions));
generateQuestion();
}
public void start (View view) {
startButton.setVisibility(View.INVISIBLE);
game.setVisibility(View.VISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton =(Button) findViewById(R.id.startButton);
sumText = (TextView) findViewById(R.id.sumTextView);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
resultTextView = (TextView) findViewById(R.id.resultTextView);
pointText = (TextView) findViewById(R.id.pointsTextView);
timertext = (TextView) findViewById(R.id.timerTextView);
playAgain = (Button) findViewById(R.id.playAgain);
game = (RelativeLayout) findViewById(R.id.gamelayout) ;
playAgain(findViewById(R.id.playAgain));
}
}
please help me to adjust my code so that I the app can use all operators instead of just addition. I have tried to do it but I have only managed to create the array list for the operators but I could not find a way to change the code to include all of the operators.

Try this:
ArrayList<Double> answers=new ArrayList<Double>();
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
char op = ops[random.nextInt(4)];
double correctAns=0;
switch(op){
case '+' : correctAns = a+b;
break;
case '/' : correctAns = (double)a/b;
break;
case '*' : correctAns = a*b;
break;
case '-' : correctAns = a-b;
break;
}
sumText.setText(Integer.toString(a) + op + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(correctAns);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer != correctAns) {
incorrectAnswer = random.nextInt(41);
}
answers.add((double)incorrectAnswer);
}
}
button1.setText(Double.toString(answers.get(0)));
button2.setText(Double.toString(answers.get(1)));
button3.setText(Double.toString(answers.get(2)));
button4.setText(Double.toString(answers.get(3)));
}
change ArrayList<Integer> answers=new ArrayList<Integer>(); to ArrayList<Double> answers=new ArrayList<Double>(); (int/int can be a double)
create a double variable contains the right answer (int/int can be a double)
choose an operation randomly.
use switch to define what operation is needed on a and bin case that every operation selected.
set the text to Integer.toString(a) + op + Integer.toString(b) instead of Integer.toString(a) + "+" + Integer.toString(b)
swap a+b to correctAns

Related

when i clicked on two imageviews which are overlapped, one of them gives me feedback the other does not

Here is codes, and i am trying to receive a feedback from imageviews which are overlapped. One of the imageviews return isPressed method true, but the other one return me false. They are overlapped, so when i clicked one of them, both of their isPressed method should be true, i guess. Where am i wrong
public class MainActivity extends AppCompatActivity {
private final String TAG = this.getClass().getSimpleName();
ImageView[] imageViews;
Button button;
int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayout gridLayout = findViewById(R.id.grid_layout);
GridLayout.LayoutParams[] layoutParams = new GridLayout.LayoutParams[9];
imageViews = new ImageView[18];
button = findViewById(R.id.button);
for (int i = 0, j = 0, k = -1, m = 0; j < 3 & k < 3 & m < imageViews.length || i < layoutParams.length; m++) {
if (m == 18) {
break;
}
if (m == 0) {
k++;
}
layoutParams[i] = new GridLayout.LayoutParams();
layoutParams[i].setGravity(Gravity.CENTER);
layoutParams[i].setMargins(25, 25, 25, 25);
layoutParams[i].columnSpec = GridLayout.spec(k, GridLayout.CENTER);
layoutParams[i].rowSpec = GridLayout.spec(j, GridLayout.CENTER);
imageViews[m] = new ImageView(MainActivity.this);
imageViews[m].setLayoutParams(layoutParams[i]);
gridLayout.addView(imageViews[m]); //---
if (m % 2 == 0) {
imageViews[m].setImageResource(R.drawable.first_image);
imageViews[m].setAlpha(1f);
} else {
imageViews[m].setImageResource(R.drawable.second_image);
imageViews[m].setAlpha(0.5f);
}
if (m % 2 == 1 & m != 0) {
j++;
i++;
}
if (m % 6 == 5 & m != 0) {
k++;
}
if (j == 3) {
j = 0;
}
}
actionView();
}
public void actionView() {
for (int m = 0; m < imageViews.length; m++) {
imageViews[m].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, " " + a + " " + "\n", Toast.LENGTH_SHORT).show();
Log.e(TAG, imageViews[1].isPressed() + "");
Log.e(TAG, imageViews[0].isPressed() + "");
Log.e(TAG, imageViews[1].isEnabled() + "");
Log.e(TAG, imageViews[0].isEnabled() + "");
Log.e(TAG, "--------------------");
a++;
for (int x = 0; x < imageViews.length; x++) {
if (imageViews[x].isPressed()) {
Log.e(TAG, x + " Image is clicked");
Log.e(TAG, " *****************");
}
}
}
});
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = 0;
}
});
}
}
If the views are overlapped and click is enabled for both only the view on top will receive the click event.
If you want to call on click event of both, call performClick of the view in background form the onclick listener of the view in front.
Like imageviewInBack.performClick()

How to count sum total in Java using Android Studio

I just learned Java using Android Studio.
My code error for use integer to count sum.
I try to decode string to integer but still error.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtvalue = (EditText) findViewById(R.id.value);
final Spinner edtjw = (Spinner) findViewById(R.id.spinner1);
txtpa = (TextView) findViewById(R.id.pa);
txttotal = (TextView) findViewById(R.id.total);
btncount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = edtvalue.getText().toString().trim();
String jw = edtjw.getSelectedItem().toString().trim();
double h = Double.parseDouble(value);
double j = Double.parseDouble(jw);
String numbertostring = String.format ("%.2f", (0.02*h));
String numbertostring2 = String.format ("%.2f", (0.025*h));
String numbertostring3 = String.format ("%.2f", (0.0275*h));
if (j == 1){
txtpa.setText(numbertostring);
} else if (j ==2){
txtpa.setText(numbertostring);
} else if (j ==3){
txtpa.setText(numbertostring);
} else if (j ==4){
txtpa.setText(numbertostring2);
} else if (j ==5){
txtpa.setText(numbertostring3);
} else {
txtpa.setText(0);
}
int tot = (h*j)+txtpa;
txttotal.setText("Total : " + tot);
}}
By looking at the code snippet, you should get string value from txtpa which is of type TextView, then parse it into double
double tot = (h*j)+Double.parseDouble(txtpa.getText().toString());
as mentioned in the above comment by Naitik Soni.

How can I generate different random numbers regularly in 4 second?

I'm trying to write a bingo game code. I want to produce 70 random numbers that change every 4 seconds.
I created a countdowntimer and created a random number in 4 seconds by defining a runnable into the finnish section in countdowntimer. But these random numbers may not be different from each other.
Handler handler;
Runnable run;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
int i = random.nextInt(70);
Random random2 = new Random();
int z = random2.nextInt(70);
int y =random2.nextInt(70);
int x =random2.nextInt(70);
int w =random2.nextInt(70);
int q =random2.nextInt(70);
int v =random2.nextInt(70);
int m =random2.nextInt(70);
int n =random2.nextInt(70);
int l =random2.nextInt(70);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
final TextView textView4 = (TextView) findViewById(R.id.textView4);
final TextView textView5 = (TextView) findViewById(R.id.textView5);
final TextView textView6 = (TextView) findViewById(R.id.textView6);
final TextView textView7 = (TextView) findViewById(R.id.textView7);
final TextView textView8 = (TextView) findViewById(R.id.textView8);
final TextView textView9 = (TextView) findViewById(R.id.textView9);
final TextView textView10 = (TextView) findViewById(R.id.textView10);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
final int a = Integer.parseInt(textView3.getText().toString());
final int b = Integer.parseInt(textView4.getText().toString());
final int c = Integer.parseInt(textView5.getText().toString());
final int d = Integer.parseInt(textView6.getText().toString());
final int e = Integer.parseInt(textView7.getText().toString());
final int f = Integer.parseInt(textView8.getText().toString());
final int g = Integer.parseInt(textView9.getText().toString());
final int h = Integer.parseInt(textView10.getText().toString());
textView9.setText("" + z);
textView10.setText(" "+ y);
textView8.setText(" "+ x);
textView7.setText(" "+ w);
textView6.setText(" "+ q);
textView5.setText(" "+ l);
textView4.setText(" "+ m);
textView3.setText(" "+ n);
CountDownTimer ct0 = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Remaining time: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
}
}.start();
CountDownTimer ct1 = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
int[] numbers = new int[70];
Random random = new Random();
int i = random.nextInt(70);
TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
if ( i == a) {
textView3.setText("ok");
} else if (i == b) {
textView4.setText("ok");
} else if (i == c) {
textView5.setText("ok");
} else if (i == d) {
textView6.setText("ok");
} else if (i == e) {
textView7.setText("ok");
} else if(i == f) {
textView8.setText("ok");
} else if (i == g) {
textView9.setText("ok");
} else if (i == h) {
textView10.setText("ok");
}
handler.postDelayed(this, 4000);
}
};
handler.post(run);
}
}.
start();
}
For 60 seconds, I want to create 70 different numbers every 4 seconds and match these numbers to the other 8 variables. I'd appreciate it if you could help. thanks.
I can give to you a way to do this, to avoid what you are saying :
But these random numbers may not be different from each other.
That's obvious because you do not control it.
I'd say to create a a Set<Integer> of your size that is 70, so you can fill this array doing a simple for loop.
for (int i = 0; i<70; i++) yourSetList.add(i);
Then a good way to "simulate" the bingo is shuffling the list, so you can use
Collections shuffle
Then you can generate a random like this :
Random random = new Random();
int random = random.nextInt(yourSetList.size()) + 1;
Then use random as an index
yourSetList.get(random);
Make sure you remove it from the list to avoid your initial problem
yourSetList.remove(random);

Not able to display very large calculation value in editext

private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .
I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.

How to make simple calculator give back the final result in EditText on android

i'm now in java and eclipse, i just tried to build a simple calculator, but i can't make it to return with the result.
My plan was basicly that when the user click one of the operators, and the EditText isn't empty, then First variable will be equal with the EditText, and the Operator variable change, and when the user hit Result button, and the First variable isn't empty, then the the EditText will be equal with the Second variable, and the Result variable will be equal with the result basicly. I think i messed up something with the types and variables, but i can't figure it out what exactly.
Could someone help?
Here is the java code;
public class Main extends Activity implements OnClickListener {
LinearLayout linear;
float First, Second, Operator, Result;
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, bResult, bTizedes, bSzorzas, bKivonas, bOsztas, bOsszeadas;
EditText eT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
First = 0;
Second = 0;
Operator = 0;
Result = 0;
b0 = (Button) findViewById(R.id.b0);
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
b4 = (Button) findViewById(R.id.b4);
b5 = (Button) findViewById(R.id.b5);
b6 = (Button) findViewById(R.id.b6);
b7 = (Button) findViewById(R.id.b7);
b8 = (Button) findViewById(R.id.b8);
b9 = (Button) findViewById(R.id.b9);
bTizedes = (Button) findViewById(R.id.bTizedes);
bSzorzas = (Button) findViewById(R.id.bSzorzas);
bResult = (Button) findViewById(R.id.bEgyenlo);
bKivonas = (Button) findViewById(R.id.bKivonas);
bOsztas = (Button) findViewById(R.id.bOsztas);
bOsszeadas = (Button) findViewById(R.id.bOsszeadas);
eT = (EditText) findViewById(R.id.eT);
b0.setOnClickListener(this);b1.setOnClickListener(this);b2.setOnClickListener(this);b3.setOnClickListener(this);
b4.setOnClickListener(this);b5.setOnClickListener(this);b6.setOnClickListener(this);b7.setOnClickListener(this);
b8.setOnClickListener(this);b9.setOnClickListener(this);bTizedes.setOnClickListener(this);bSzorzas.setOnClickListener(this);
bResult.setOnClickListener(this);bKivonas.setOnClickListener(this);bOsztas.setOnClickListener(this);bOsszeadas.setOnClickListener(this);
bSzorzas.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(First == 0)
{
EditText eT = (EditText) findViewById(R.id.eT);
float First = Float.valueOf(eT.getText().toString());
Operator = 2;
eT.setText(null);
}
else if(First != 0)
{
Operator = 2;
};
}
});
bKivonas.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(First == 0)
{
EditText eT = (EditText) findViewById(R.id.eT);
float First = Float.valueOf(eT.getText().toString());
Operator = 4;
eT.setText(null);
}
else if(First != 0)
{
Operator = 4;
};
}
});
bOsztas.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(First == 0)
{
EditText eT = (EditText) findViewById(R.id.eT);
float First = Float.valueOf(eT.getText().toString());
Operator = 1;
eT.setText(null);
}
else if(First != 0)
{
Operator = 1;
};
}
});
bOsszeadas.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(First == 0)
{
EditText eT = (EditText) findViewById(R.id.eT);
float First = Float.valueOf(eT.getText().toString());
Operator = 3;
eT.setText(null);
}
else if(First != 0)
{
Operator = 3;
};
}
});
bResult.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if(First != 0)
{
EditText eT = (EditText) findViewById(R.id.eT);
float Second = Float.valueOf(eT.getText().toString());
if(Operator == 1){
int Result = (int) (First) / (int) (Second);
eT.setText(Result);
}
else if(Operator == 2){
int Result = (int) (First) * (int) (Second);
eT.setText(Result);
}
else if(Operator == 3){
int Result = (int) (First) + (int) (Second);
eT.setText(Result);
}
else if(Operator == 4){
int Result = (int) (First) - (int) (Second);
eT.setText(Result);
}
eT.setText(null);
}
else if(First == 0)
{
};
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.b0:
eT.setText( eT.getText() + "0");
break;
case R.id.b1:
eT.setText( eT.getText() + "1");
break;
case R.id.b2:
eT.setText( eT.getText() + "2");
break;
case R.id.b3:
eT.setText( eT.getText() + "3");
break;
case R.id.b4:
eT.setText( eT.getText() + "4");
break;
case R.id.b5:
eT.setText( eT.getText() + "5");
break;
case R.id.b6:
eT.setText( eT.getText() + "6");
break;
case R.id.b7:
eT.setText( eT.getText() + "7");
break;
case R.id.b8:
eT.setText( eT.getText() + "8");
break;
case R.id.b9:
eT.setText( eT.getText() + "9");
break;
}
}}
Try to focus on this Tutorial and see how things are done, Also try to improve it
float First = Float.valueOf(eT.getText().toString());
2 problems:
Why re-declare your variable First here? Simply use it.
To parse, use Float.parseFloat(eT.getText().toString());
And why do you name your variables as First? use first.Follow conventions.
EDIT:
Could see the same issue of re-declaring almost all your variables. Please don't do that.

Categories