2 counters not appearing at the same time in android - java

I am new to android and java and im trying my best to do a simple game called rockpaper scissor.
I am wondering why does my code cScore = 0; wont appear at the same time with yScore=0. I need to press again the rock button to reset the cScore back to 0.
Please help, any kind of suggestions will do.
thanks.
public class MainActivity extends AppCompatActivity {
TextView youOutput, compOutput, youScore, compScore;
int yScore=0, cScore=0, cPicked;
Random abc = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youOutput =(TextView)findViewById(R.id.youOutput);
compOutput = (TextView)findViewById(R.id.compOutput);
youScore = (TextView)findViewById(R.id.youScore);
compScore = (TextView)findViewById(R.id.compScore);
}
public void rockButton(View view) {
youOutput.setText("Rock");
cPicked = 1+abc.nextInt(3);
if (cPicked == 1) {
compOutput.setText("Rock");
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else if(cPicked == 2) {
compOutput.setText("Paper");
cScore++;
if(cScore == 10){
cScore = 0;
yScore = 0;
Toast.makeText(this, "Computer won", Toast.LENGTH_LONG).show();
}else
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else {
compOutput.setText("Scissor");
yScore++;
if(yScore == 10){
cScore = 0;
yScore = 0;
Toast.makeText(this, "You won", Toast.LENGTH_LONG).show();
}else
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
}

Add curly brackets in last else block and else block in if (cPicked == 2)
if (cPicked == 1) {
compOutput.setText("Rock");
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
} else if (cPicked == 2) {
compOutput.setText("Paper");
cScore++;
if (cScore == 10) {
cScore = 0;
yScore = 0;
Toast.makeText(this, "Computer won", Toast.LENGTH_LONG).show();
//added curly brackets
} else {
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
} else {
compOutput.setText("Scissor");
yScore++;
if (yScore == 10) {
cScore = 0;
yScore = 0;
Toast.makeText(this, "You won", Toast.LENGTH_LONG).show();
//added curly brackets
} else {
compScore.setText(Integer.toString(cScore));
youScore.setText(Integer.toString(yScore));
}
}

Related

Best way to run a function 10 times, at 10 second intervals

Basically I have a function that loads questions for a trivia game. Each game has 10 rounds. Currently I have it in a four loop and tried using CountDownTimer but it would still iterate through and call the function 10 times right away. Just looking on some advice on how to call a round that lasts 10 seconds and then move to the next round.
public class GameActivity extends AppCompatActivity {
int questionCount = 0;
int textUpdate = 0;
Boolean readFlag = true;
Button answerOneBtn, answerTwoBtn, answerThreeBtn, answerFourBtn;
TextView questionTextView;
int playerScore = 0;
Game currentGame = new Game(questionCount, readFlag, playerScore);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
currentGame.questionList.AnswersJumbled();
for(int i = 0; i < 10; i++) {
Log.e("Error", "For Loop is Running");
playGame();
}
answerOneBtn = findViewById(R.id.AnswerOneButton);
answerTwoBtn = findViewById(R.id.AnswerTwoButton);
answerThreeBtn = findViewById(R.id.AnswerThreeButton);
answerFourBtn = findViewById(R.id.AnswerFourButton);
questionTextView = findViewById(R.id.questionText);
answerOneBtn.setOnClickListener(v -> {
currentGame.playerOneSelection = answerOneBtn.getText().toString();
Log.e("error", currentGame.playerOneSelection);
});
answerTwoBtn.setOnClickListener(v -> {
currentGame.playerOneSelection = answerTwoBtn.getText().toString();
Log.e("error", currentGame.playerOneSelection);
});
answerThreeBtn.setOnClickListener(v -> {
currentGame.playerOneSelection = answerThreeBtn.getText().toString();
Log.e("error", currentGame.playerOneSelection);
});
answerFourBtn.setOnClickListener(v -> {
currentGame.playerOneSelection = answerFourBtn.getText().toString();
Log.e("error", currentGame.playerOneSelection);
});
}
public void playGame() {
answerOneBtn = findViewById(R.id.AnswerOneButton);
answerTwoBtn = findViewById(R.id.AnswerTwoButton);
answerThreeBtn = findViewById(R.id.AnswerThreeButton);
answerFourBtn = findViewById(R.id.AnswerFourButton);
questionTextView = findViewById(R.id.questionText);
currentGame.loadQuestion(questionCount);
questionTextView.setText(currentGame.currentQuestion);
answerOneBtn.setText(currentGame.firstAnswer);
answerTwoBtn.setText(currentGame.secondAnswer);
answerThreeBtn.setText(currentGame.thirdAnswer);
answerFourBtn.setText(currentGame.fourthAnswer);
questionCount++;
}
}
Okay, so after a bit of digging and being pointed in a general direction by the comments I found that the right answer was a handler.
My for loop now looks like this
for (int i = 0; i < 10; i++) {
handler.postDelayed(() -> playGame(), 10000 * i);
playerAnswered = false;
playerScore += currentGame.checkPlayerAnswer(currentGame.playerOneSelection);
}

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()

Where should I place my increment?

I'm having a hard time figuring out where I should put my ers++ or ers+=1. I've tried doing a for loop and do-while, it worked and reached the limit of 3, but it should also let the user input again and check the inputs again.
if (ers < 3) {
if (a.equals(SignupPage.ee) && b.equals(SignupPage.dd) && !(a.isEmpty()) && !(b.isEmpty())) {
System.out.println(a+" "+b);
tf = true;
JOptionPane.showMessageDialog(null, "Welcome!", "Payment Portal", JOptionPane.INFORMATION_MESSAGE);
ElectricityPage ep = new ElectricityPage();
ep.setVisible(true);
} else if (a.equals("Admin") && b.equals("javaness") && !(a.isEmpty()) && !(b.isEmpty())) {
SignupPage.aa = Admin.Fname[0];
SignupPage.aa = Admin.Lname[0];
ers+=1;
ElectricityPage ep = new ElectricityPage();
ep.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "something is wrong", "Payment Portal", JOptionPane.ERROR_MESSAGE);
//ers=ers+1;
}
System.out.println(ers);
}

Line of code ignored

I'm trying to clean my code to make it run under 'sections'.
There's one called intro(), another one called second() and so on..
The issue comes when I switch from the first section of code (intro()) to the next one (second()) which should run a cleaning code first, but doesn't really!
The code basically writes text on a list which should look like a chat, so the intro() is the first part of text then it should clear the chat and start writing other text inside second().
This is my code, take a look:
int counter;
boolean introDone = false;
//Intro
public void intro(){
write(answers[counter], buttonText[counter]);
}
public void second(){
write("So these are the rules:", R.string.go);
}
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
if(counter <= 2){
intro();
}else if(counter == 3){
clear();
}else if (counter > 2 && counter < 5) {
second();}
counter++;
}
}
This did the trick:
//Intro
public void intro(){
write(answers[counter], buttonText[counter]);
}
public void second(){
write("So these are the rules:", R.string.go);
}
public void hello(View view) {
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
if (counter <= 2) {
intro();
} else if(counter == 3) {
introDone = true;
}
if (introDone) {
clear();
introDone = false;
}
if (counter > 2 && counter < 5) {
second();
}
counter++;
}
}
How is the variable counter and the variable introDone initialized?
I assume that the variable counter have the value 0 at the start of the program, and the variable introDone is false. If that is the case, then the code into second section isn't executed. Example:
public void hello(View view){
// --> here, counter=0 and introDone=false
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
intro(); // --> counter is still 0, so the variable introDone is still false
second(); // --> because introDone=false then the code is not executed
counter++;
}
I'm going to assume that the boolean introDone variable is never true. In your intro() method you have it wrapped with an if statement to check if the counter is 2 or less. It is hard to tell without the full source, but I would guess that if you changed your code to this:
//Intro
public void intro(){
//if (counter <= 2) {
// write(answers[counter], buttonText[counter]);
//}else{
introDone = true;
//}
}
public void second(){
if(introDone) {
listViewMother.setAdapter(null); //THIS SHOULD CLEAN THE LIST, BUT INSTEAD WHEN I RUN THE CODE IT LOOKS LIKE IT JUST IGNORES IT
if (counter > 2 && counter < 5) {
write("So these are the rules:", R.string.go);
}
}
}
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
intro();
second();
counter++;
}
everything would work fine.
From there you could look at the logic around how you increment the counter variable and see if that was the issue.
This example will run call intro() and second() 10 times.
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
for (int counter = 0; counter < 10; counter++) {
intro();
second();
}
}

Why does it call method 'isCorrect' multiple times (onClick) if I hit the button only once?

I made a simple quiz game for android, right now there's only 10 questions, and 40 answers. (4 answers for each question)
Sometimes when I hit a button it gives me more than one correct answer at a time, also it might even do it when answer's not correct.
Any idea what's wrong in this code? Cause Im not calling the isCorrect boolean method multiple times (in one click).
Code:
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
tip;
private String a1,a2,a3,a4 = "";
private int i1 = 0;
public static int correct = 0;
private boolean alive = true;
MediaPlayer button_click;
private String[] questions =
{"Q1",
"Q2",
"Q3",
"Q4",
"Q5", //5
"Q6",
"Q7",
"Q8",
"Q9",
"Q10" //10
};
public static int question_amount = 10;
private String[] answers_correct =
{"Correct answer - 1",
"Correct answer - 2",
"Correct answer - 3",
"Correct answer - 4",
"Correct answer - 5",
"Correct answer - 6",
"Correct answer - 7",
"Correct answer - 8",
"Correct answer - 9",
"Correct answer - 10"
};
private String[][] answers_wrong =
{ {"Q1-1", "Q1-2" , "Q1-3"},
{"Q2-1", "Q2-2" , "Q2-3"},
{"Q3-1", "Q3-2" , "Q3-3"},
{"Q4-1", "Q4-2" , "Q4-3"},
{"Q5-1", "Q5-2" , "Q5-3"},
{"Q6-1", "Q6-2" , "Q6-3"},
{"Q7-1", "Q7-2" , "Q7-3"},
{"Q8-1", "Q8-2" , "Q8-3"},
{"Q9-1", "Q9-2" , "Q9-3"},
{"Q10-1", "Q10-2" , "Q10-3"}
};
List<String> question_list = new ArrayList<String>();
List<String> answer_list_correct = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData();
Game(i1);
}
#Override
public void onClick(View view) {
if (alive == false) {
// startActivity(new Intent("com.aleksei.etb.END"));
return;
}
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
break;
case R.id.button1: //answer_1
if(isCorrect(1))
correct++;
break;
case R.id.button2: //answer_2
if(isCorrect(2))
correct++;
break;
case R.id.button3: //answer_3
if(isCorrect(3))
correct++;
break;
case R.id.button4: //answer_3
if(isCorrect(4))
correct++;
break;
default:
break;
}
Game(i1);
tip.setText("Correct answers: "+correct);
}
public static int getResults(){
int value = (int) Math.floor((correct*5)/question_amount);
if(value <= 0)
return 1;
else
return value;
}
private boolean isCorrect(int button){
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && a1 == answers_correct[i]
|| button == 2 && a2 == answers_correct[i]
|| button == 3 && a3 == answers_correct[i]
|| button == 4 && a4 == answers_correct[i])
return true;
}
return false;
}
private void Game(int q){
if(i1 == question_amount) { //no more questions
startActivity(new Intent("com.aleksei.etb.END"));
alive = false;
return;
}
try {
main.setText("Dunno");
String answer_list[] = {
answers_correct[q], answers_wrong[q][0] , answers_wrong[q][1] , answers_wrong[q][2]
};
Collections.shuffle(Arrays.asList(answer_list));
answer_1.setText(answer_list[0]);
answer_2.setText(answer_list[1]);
answer_3.setText(answer_list[2]);
answer_4.setText(answer_list[3]);
a1 = answer_list[0];
a2 = answer_list[1];
a3 = answer_list[2];
a4 = answer_list[3];
q_textview.setText(questions[q]);
} catch (Exception ex){}
i1++;
}
private void getData(){
//Getting the data
main = (Button) findViewById(R.id.button5);
answer_1 = (Button) findViewById(R.id.button1);
answer_2 = (Button) findViewById(R.id.button2);
answer_3 = (Button) findViewById(R.id.button3);
answer_4 = (Button) findViewById(R.id.button4);
q_textview = (TextView) findViewById(R.id.question);
tip = (TextView) findViewById(R.id.answ1);
//Making the buttons, actually work
main.setOnClickListener(this);
answer_1.setOnClickListener(this);
answer_2.setOnClickListener(this);
answer_3.setOnClickListener(this);
answer_4.setOnClickListener(this);
//Resets the text
//Note to self: Replace with another ContectView
main.setText("Begin!");
answer_4.setText("");
answer_3.setText("");
answer_2.setText("");
answer_1.setText("");
tip.setText("");
}
}
Consider the following changes and see if it improves:
private int questionNumber = -1;
private void Game(int q){
...
questionNumber = q;
q_textview.setText(questions[q]);
...
}
private boolean isCorrect(int button){
if(button == 1 && a1.equals(answers_correct[questionNumber])
|| button == 2 && a2.equals(answers_correct[questionNumber])
|| button == 3 && a3.equals(answers_correct[questionNumber])
|| button == 4 && a4.equals(answers_correct[questionNumber]))
return true;
}
return false;
}
Storing the question number as a field eliminates the for loop over all the questions.
You should always use String.equals instead of ==.

Categories