I try to create a vocabulary loop in android - java

I am trying to make an app that alike vocabulary card.
I have an Answer array(array size = 4).
I am creating random an english word then I am adding true value of english word in answer array and I am removing true value of english word in turkish array in order to not use again in random.I am doing same things to other answer array include wrong value.
Problem is that array size is going to 0.for example my total array 20 .when I remove true value,array size is going to 19-18-17... per click then program close.
Here is my code:
package de.murattekinlive.pwords;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class WordsActivity extends AppCompatActivity {
TextView textView;
TextView deneme;
DataBase dataBase;
Button btn_r1,btn_r2,btn_r3,btn_r4;
String [] TR_WORDS;
String [] EN_WORDS;
String [] Answer;
int control_id = 0;
int random ;
Random control;
Random rnd;
int tr,en;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_words);
textView = (TextView) findViewById(R.id.textView);
deneme = (TextView) findViewById(R.id.textView3);
dataBase = new DataBase(getApplicationContext());
rnd= new Random();
btn_r1 = (Button)findViewById(R.id.button_random1);
btn_r1.setOnClickListener(new myClickListener());
btn_r2 = (Button)findViewById(R.id.button_random2);
btn_r2.setOnClickListener(new myClickListener());
btn_r3 = (Button)findViewById(R.id.button_random3);
btn_r3.setOnClickListener(new myClickListener());
btn_r4 = (Button)findViewById(R.id.button_random4);
btn_r4.setOnClickListener(new myClickListener());
ArrayList<Words> enWordlist = (ArrayList<Words>) dataBase.allEnWords();
ArrayList<Words> trWordlist =(ArrayList<Words>) dataBase.allTrWords();
TR_WORDS = new String[trWordlist.size()];
EN_WORDS = new String[enWordlist.size()];
for(int i=0;i<enWordlist.size();i++){
EN_WORDS[i] =enWordlist.get(i).getWORD().toString();
TR_WORDS[i] =trWordlist.get(i).getTR1().toString();
}
tr = new Random().nextInt(TR_WORDS.length);
/*btn_r1.setText(TR_WORDS[en]);
btn_r2.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r3.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);
btn_r4.setText(TR_WORDS[new Random().nextInt(TR_WORDS.length)]);*/
ReStart();
}
private class myClickListener implements View.OnClickListener{
public void onClick(View v){
switch ( v.getId() ) {
case R.id.button_random1:
break;
case R.id.button_random2:
break;
case R.id.button_random3:
break;
case R.id.button_random4:
break;
default:
break;
}
WordsActivity.this.ReStart();
}
}
public void ReStart(){
Answer = new String[4];
control = new Random();
control_id = control.nextInt(4);
en = new Random().nextInt(EN_WORDS.length);
final List<String> newTRList = new ArrayList<>();
textView.setText(EN_WORDS[en]);
final int sayi1,sayi2;
sayi1 = TR_WORDS.length;
Collections.addAll(newTRList,TR_WORDS);
// I added true turkish word in answer array
for(int i=0;i<TR_WORDS.length;i++){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
TR_WORDS = newTRList.toArray(new String[newTRList.size()]);
//I added another values in answer array and I want to remove values that is used because
//I dont want to see same value in answer array.
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random=rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
sayi2 =TR_WORDS.length;
deneme.setText(sayi1+"/"+sayi2);
for(int i=0;i<=3;i++){
if(i == control_id){
}
else if(i == 0){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 1){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 2){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
else if(i == 3){
random =rnd.nextInt(TR_WORDS.length);
Answer[i]=TR_WORDS[random];
}
}
for(int j=0;j<=3;j++){
if(j==0){
btn_r1.setText(Answer[j].toString());
}
else if(j==1){
btn_r2.setText(Answer[j].toString());
}
else if(j==2){
btn_r3.setText(Answer[j].toString());
}
else if(j==3){
btn_r4.setText(Answer[j].toString());
}
}
}
}

Change your for loop to:
for(int i=TR_WORDS.length; i >=0 ;i--){
if(en == i){
Answer[control_id]=TR_WORDS[i].toString();
newTRList.remove(TR_WORDS[i].toString()); //remove true value from array in order to not use again.
}
}
And all the other ones that include a remove in a similar a fashion.

Related

What does array do in this code?

I am studying on udemy. I was writing the code of XOX game. I think all of us know XOX game. My code is working but i didn't understand what does this code do ?
for (int [] winningPosition : winningPositions){
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)}
The code which is the i dont get is above. Please help me with understand that.
{ package com.example.anild.xox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// 0 = yellow, 1 = red
int activePlayer = 0;
boolean gameIsActive = true;
//2 means unplayed
int [] gameState = {2,2,2,2,2,2,2,2,2};
int [][] winningPositions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
public void dropIn(View view) {
ImageView counter = (ImageView) view;
int tappedCounter = Integer.parseInt(counter.getTag().toString());
if(gameState[tappedCounter] == 2 && gameIsActive) {
//burada tappedCounterdaki sayıyı çekiyor yani tag'i daha sonra gamstate[] dizisine atıyor. Ve zaten hepsi 2 if koşulu sağlanıyor
//Bir asağısında bu kural değişiyor. Bu alınan tag gametate'te artık 0 olarak saklanıyor :)
gameState[tappedCounter] = activePlayer;
counter.setTranslationY(-1000f);
if (activePlayer == 0) {
counter.setImageResource(R.drawable.yellow);
activePlayer = 1;
} else {
counter.setImageResource(R.drawable.red);
activePlayer = 0;
}
counter.animate().translationYBy(1000f).rotation(360).setDuration(300);
for (int [] winningPosition : winningPositions){
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2){
//someone has won
gameIsActive = false;
String winner = "Red";
if(gameState[winningPosition[0]] == 0){
winner = "Yellow";
}
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText(winner + "has won !");
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
}
else {
boolean gameIsOver = true;
for(int counterState : gameState) {
if (counterState == 2) {
gameIsOver = false;
}
if (gameIsOver) {
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText("it's a draw");
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
}
}
}
}
}
}
public void playAgain(View view) {
gameIsActive = true;
LinearLayout layout = (LinearLayout)findViewById(R.id.playAgainLayout);
layout.setVisibility(View.INVISIBLE);
// 0 = yellow, 1 = red
activePlayer = 0;
for(int i = 0; i < gameState.length; i++) {
gameState[i] = 2;
}
GridLayout gridLayout = (GridLayout) findViewById(R.id.gridLayout);
for(int i = 0; i < gridLayout.getChildCount(); i++) {
((ImageView) gridLayout.getChildAt(i)).setImageResource(0);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
Answering based on the question posed below my comment:
At it's most fundamental, the format for that for loop is
for('one object' : 'group of objects')
Now then, under ordinary circumstances you'd use something along the lines of:
for(String oneString : arrayOfStrings)
Based on your question, it appears as if you are unaware that you can statically specify an array of values by putting them inside braces. For example:
String[] arrayOfStrings = {"zero", "one", "two"};
That produces exactly the same result as:
String[] arrayOfStrings = new String[3];
arrayOfStrings[0] = "zero";
arrayOfStrings[1] = "one";
arrayOfStrings[2] = "two";
You could loop over that with for(String string : arrayOfStrings)...
Going back to your original code - they have embedded braces inside braces, which is how you declare a multi-dimensional array. So the following:
int [][] winningPositions = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
Produces the same array as:
int[][] winningPositions = new int[8][3];
winningPositions[0][0] = 0;
winningPositions[0][1] = 1;
winningPositions[0][2] = 2;
...
winningPositions[7][0] = 2;
winningPositions[7][1] = 4;
winningPositions[7][2] = 6;
With me so far?
The full "winningPositions" variable is an object of type array, whose content is itself a sequence of arrays. Okay, so now when you do your loop that you don't understand, this:
for (int [] winningPosition : winningPositions)
Each item in the array "winningPosition" is itself an array - as I just said - so the "one object" resolves to the inner array, which has 3 elements, while the outer has 8.
Does that help?
On a side note: Code like that is either aimed at new programmers, or else is written by someone that doesn't understand OO programming. It's worthwhile to understand how it works, it is not necessarily meant to be emulated. Or at least by the time you know I'm wrong about that, you'll know why I'm wrong.
for (int [] winningPosition : winningPositions)
Iterates through the array called winningPositions. Each iteration has the variable called winningPosition which is an int array of length 3.
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)
checks that all the positions are owned by the same player and the last part gameState[winningPosition[0]] != 2 checks that the line isn't empty.
EDIT:
#ChrisParker explains this line very well in the comments. for (int [] winningPosition : winningPositions)
The for loop is iterating through the array and checking each of the conditions inside the if statement, IF all of them are true then the code will go inside the IF loop otherwise it will skip over and continue.
Cheers

Possible bug in android?

I guess that for some reason, the program below is passing by through conditions verifications and executing next condition's lines...
This program of mine should add the values 4 and 0 to the listIntercedeOut, but it removes right after adding them to the list...
If we put an empty for() right after the listIntercedeOut.add() methods, it doesn't remove
after...
Also, if we disable both listIntercedeOut.remove() lines commented on the code, the code works either...
I've made a little interface with TextView and Button to check list's values, I've made a lot of modifications from my main program... Those "almost-empty" conditions are needed there...
Also, that intercede(boolean) method will always return true in the example.
AddDisciplina.java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AddDisciplina extends AppCompatActivity {
Button buttonCheck;
TextView text;
private List<Integer> listIntercedeIn = new ArrayList<>();
private List<Integer> listIntercedeOut = new ArrayList<>();
private SparseArray<String> sparseSeg=new SparseArray<>();
String time = "00:00";
String time2 = "01:30";
int var = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_add_disciplina);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getSupportActionBar().setHomeButtonEnabled(true);
buttonCheck = (Button)findViewById(R.id.buttonCheck);
text = (TextView)findViewById(R.id.text);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String items="";
for(int i = 0; i < listIntercedeOut.size(); i++){
items = items + "-" + String.valueOf(listIntercedeOut.get(i));
}
text.setText(items);
}
});
sparseSeg.put(0, "01:00/02:00");
sparseSeg.put(4, "00:00/01:30");
abrirTimePicker(false);
}
private void abrirTimePicker(final boolean inicio){
if(inicio) {
if (time.equals("")) {
}
} else {
if((1<0)||(1==0 && 30<=0)){
}
switch (var){
case 3:
for (int i = 0; i < sparseSeg.size(); i++) {
String[] hs = sparseSeg.valueAt(i).split("/");
int idDoLL = sparseSeg.keyAt(i);
if ((inicio && !hs[1].equals("vazio") && intercede(hs[0], hs[1], time, time2)) ||
(!inicio && !hs[1].equals("vazio") && intercede(time, time2, hs[0], hs[1]))) {
if (inicio) { // DO SOMETHING
} else {
// SHOULD ALWAYS END HERE //
listIntercedeOut.add(4);
listIntercedeOut.add(idDoLL);
// IF WE RELEASE THIS FOR, EVERYTHING WORKS FINE
/*for(i = 1; i < listIntercedeOut.size(); i++) {
}*/
}
} else if (inicio && listIntercedeIn.contains(4) && listIntercedeIn.contains(0)) {
listIntercedeIn.remove(Integer.valueOf(4));
listIntercedeIn.remove(Integer.valueOf(idDoLL));
} else if (!inicio && listIntercedeOut.contains(4) && listIntercedeOut.contains(0)) {
// IF WE DISABLE THE FOLLOWING 2 LINES, EVERYTHING WORKS FINE
listIntercedeOut.remove(Integer.valueOf(4));
listIntercedeOut.remove(Integer.valueOf(0));
}
}
break;
}
}
}
private boolean intercede (String horario1, String horario2, String horario3, String horario4){
String[] hm1 = horario1.split(":");
int horas1 = Integer.parseInt(hm1[0]);
int minutos1 = Integer.parseInt(hm1[1]);
int ms1 = (horas1 * 3600000) + (minutos1 * 60000);
String[] hm2 = horario2.split(":");
int horas2 = Integer.parseInt(hm2[0]);
int minutos2 = Integer.parseInt(hm2[1]);
int ms2 = (horas2 * 3600000) + (minutos2 * 60000);
String[] hm3 = horario3.split(":");
int horas3 = Integer.parseInt(hm3[0]);
int minutos3 = Integer.parseInt(hm3[1]);
int ms3 = (horas3 * 3600000) + (minutos3 * 60000);
String[] hm4 = horario4.split(":");
int horas4 = Integer.parseInt(hm4[0]);
int minutos4 = Integer.parseInt(hm4[1]);
int ms4 = (horas4 * 3600000) + (minutos4 * 60000);
return (ms1<ms3 && ms3<ms2) || (ms1<ms4 && ms4<ms2);
}
}
add_disciplina_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text"/>
<Button
android:id="#+id/buttonCheck"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CHECK LIST"/>
</LinearLayout>
Could anyone please explain me what is going on here? Thanks in advance
There are maybe some value of your sparseSeg list who match your third condition loop . Put some log to see what's happen:
for (int i = 0; i < sparseSeg.size(); i++) {
String[] hs = sparseSeg.valueAt(i).split("/");
int idDoLL = sparseSeg.keyAt(i);
if ((inicio && !hs[1].equals("vazio") && intercede(hs[0], hs[1], time, time2)) ||
(!inicio && !hs[1].equals("vazio") && intercede(time, time2, hs[0], hs[1]))) {
if (inicio) { // DO SOMETHING
} else {
// SHOULD ALWAYS END HERE //
listIntercedeOut.add(4);
listIntercedeOut.add(idDoLL);
Log.i("1 CONDITION", i + "");
// IF WE RELEASE THIS FOR, EVERYTHING WORKS FINE
/*for(i = 1; i < listIntercedeOut.size(); i++) {
}*/
}
} else if (inicio && listIntercedeIn.contains(4) && listIntercedeIn.contains(0)) {
listIntercedeIn.remove(Integer.valueOf(4));
listIntercedeIn.remove(Integer.valueOf(idDoLL));
Log.i("2 CONDITION", i + "");
} else if (!inicio && listIntercedeOut.contains(4) && listIntercedeOut.contains(0)) {
// IF WE DISABLE THE FOLLOWING 2 LINES, EVERYTHING WORKS FINE
listIntercedeOut.remove(Integer.valueOf(4));
listIntercedeOut.remove(Integer.valueOf(0));
Log.i("3 CONDITION", i + "");
}
}
I think at least one value match to the last condition so, your values or remove from your list.
You should maybe rework your loop system condition.
Hope this helps.
Sorry for my poor english.
(I did a little correction)

Cannot Find Symbol Error with event handler

I am having trouble trying to initialize a variable correctly. Earlier I was getting a Number Format Exception because I was parsing an integer inside of an empty text field. Now I have created an if statement that checks first to see if the field is empty, then parses an integer inside of it. The problem i'm having now is that my event handler can't recognize the variable, because it is inside the if statement. I tried declaring it outside of the if statement but that didn't work either. Any tips to point me in the right direction? Here is my code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
ArrayList<Integer> deck;
deck = new ArrayList<>();
int i = 1;
while(i < 52){
deck.add(i);
i++;
}
final AtomicReference<String> result = new AtomicReference<>("go.");
Collections.shuffle(deck);
BorderPane pane = new BorderPane();
HBox top = new HBox(10);
Label display = new Label(result.toString());
Button btShuffle = new Button("Shuffle");
btShuffle.setOnAction(
e -> {
Collections.shuffle(deck);
});
top.getChildren().add(display);
top.getChildren().add(btShuffle);
HBox center = new HBox(10);
Card card1 = new Card(deck.get(0));
center.getChildren().add(card1);
Card card2 = new Card(deck.get(1));
center.getChildren().add(card2);
Card card3 = new Card(deck.get(2));
center.getChildren().add(card3);
Card card4 = new Card(deck.get(3));
center.getChildren().add(card4);
HBox bottom = new HBox(10);
Label expression = new Label("Please Enter the expression: ");
TextField tfExpress = new TextField();
LinkedList<Object> expInput = new LinkedList<>();
ArrayList<Character> signs = new ArrayList<>();
signs.add('/');
signs.add('+');
signs.add('(');
signs.add(')');
signs.add('-');
signs.add('^');
signs.add('*');
signs.add('%');
String str = tfExpress.getText();
char tempStor[] = str.toCharArray();
for(char c: tempStor){
expInput.add(c);
}
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
expInput.removeIf(p-> p.equals(signs));
Button btVerify = new Button("Verify");
btVerify.setOnAction(
(ActionEvent e) -> {
if(card1.CardValue() == (int)expInput.get(0)
&& card2.CardValue() == (int)expInput.get(1)
&& card3.CardValue() == (int)expInput.get(2)
&& card4.CardValue() == (int)expInput.get(3)){
if(express == 24){
result.set("Correct");
}
else
result.set("Incorrect");
}
else
result.set("The numbers in the expression don't "
+ "match the numbers in the set.");
});
pane.setTop(top);
pane.setCenter(center);
pane.setBottom(bottom);
Scene scene = new Scene(pane);
primaryStage.setTitle("24 card game");
primaryStage.setScene(scene);
primaryStage.show();
}
public class Card extends Pane {
public int cardVal;
Card(int card){
Image cardImage;
cardImage = new Image("card/"+ card +".png");
cardVal = card;
}
public int CardValue(){
int card = 0;
if(cardVal <= 13){
card = cardVal;
}
else if(cardVal > 13 && cardVal <= 26){
card = cardVal - 13;
}
else if(cardVal > 26 && cardVal <= 39){
card = cardVal - 26;
}
else if(cardVal > 39 && cardVal <= 52){
card = cardVal - 39;
}
return card;
}
}
public static void main(String[] args) {
launch(args);
}
}
If str being empty is an acceptable behavior for your code, you need to define a default value for express if that is the case. If the default value were -1, for example, you would do:
int express = (str != null && !"".equals(str)) ? Integer.parseInt(str) : -1;
And then later, you should treat the -1 case accordingly.
You need to initialize express like this, so it is effectively final and can be used in the lambda expression.
Instead of
if(tfExpress.getText() != null && tfExpress.getText().equals(""))
{
int express = Integer.parseInt(str);
}
try
final int express = (tfExpress.getText() != null && !tfExpress.getText().equals("")) : Integer.parseInt(str) : 0;

Java - <identifier> required/illegal start of expression [duplicate]

This question already has answers here:
Java instance variable declare and Initialize in two statements
(5 answers)
Closed 8 years ago.
I'm running into some trouble with a Java assignment. I'm not sure what I'm doing wrong, but it's telling me that I need an identifier and that the lines are an illegal start of an expression when I try to add() to an ArrayList.
Here's my code, the offender starts at printStrat.add("1. Tit-For-Tat\n"); :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.lang.Math;
public class PDGame
{
private static ArrayList<boolean> rcrd = new ArrayList();
private static Gamestat globalStats = new Gamestat();
private String[] rslt = new String[] {
"You and your partner remain silent\n",
"Your partner testifies against you and you remain silent\n",
"You testify against your partner and he remains silent\n",
"You both testify against each other\n" };
private ArrayList<String> printStrat = new ArrayList<String>();
printStrat.add("1. Tit-For-Tat\n");
printStrat.add("2. Tit-For-Two-Tats\n");
printStrat.add("3. Tit-For-Tat with forgiveness\n");
private int strat = 1;
private int npcPrison = 0;
private int pcPrison = 0;
public PDGame()
{
//there is no need for a scanner to read if I won't be doing
// anything with it, so I did not implement it
}
public String playRound(int decision)
{
boolean myMove;
if(strat == 1) { //Tit-for-Tat
if(rcrd.size() < 1) //if first move
myMove = false;
else //set npc move to last player's move
myMove = rcrd.get(rcrd.size()-1);
}
else if(strat == 2) { //Tit-for-Two-Tats
if(rcrd.size() < 2) //if first move
myMove = false;
else if(rcrd.get(rcrd.size()-1) == true && rcrd.get(rcrd.size()-2) == true)
myMove = true; //if player betrayed last two times, betray
else //otherwise, forgive
myMove = false;
}
else if(strat == 3) {
int ran = (int)(Math.random()*100+1);
if(rcrd.size() < 1) //if first move,forgive
myMove = false;
else if(ran < 50) //if ran > 75, act normally
myMove = rcrd.get(rcrd.size()-1);
else //if ran = 1-50, forgive
myMove = false;
}
if(decision == 1) {
if(myMove == false) {
result = rslt[0];
npcPrison = 2;
pcPrison = 2;
}
else if(myMove == true) {
result = rslt[1];
npcPrison = 1;
pcPrison = 5;
}
rcrd.add(false);
}
else if(decision == 2) {
if(myMove == false) {
result = rslt[2];
npcPrison = 5;
pcPrison = 1;
}
else {
result = rslt[3];
npcPrison = 3;
pcPrison = 3;
}
rcrd.add(true);
}
globalStats.update(pcPrison,npcPrison);
globalStats.setDate();
return result;
}
public ArrayList<String> getStrategies()
{
return printStrat;
}
public void setStrategy(int strategy)
{
strat = strategy;
globalStats.setStrategy(strategy);
}
public GameStat getStats()
{
return globalStats();
}
public String getScores()
{
String scores = "Your prison sentence is: " + pcPrison + "\n";
scores += "Your partner's prison sentence is " + npcPrison + "\n";
return scores;
}
}
Any and all help is appreciated.
You cannot put code (except assignments) straight under a class declaration - it should be put in a method, constructor or anonymous block. One way to solve this would be to move your calls to printStrat.add to the constructor:
public class PDGame
{
/* snipped */
private ArrayList<String> printStrat = new ArrayList<String>();
public PDGame()
{
printStrat.add("1. Tit-For-Tat\n");
printStrat.add("2. Tit-For-Two-Tats\n");
printStrat.add("3. Tit-For-Tat with forgiveness\n");
}
/* snipped */
}

Weird error + How to make this code more efficent?

as soon as I use method Game(), my app crashes, why?
Also I'd like to know if it's possible to make my code shorter in terms of space it takes & better.
Code:
package com.aleksei.etb;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
TextView tip;
private String aString[];
private int i1 = 0;
private int correct = 0;
private boolean alive = false;
MediaPlayer button_click;
private String[] questions ={"Question 1" , "Question 2","Question 5"};
private String[] answers_correct ={"Correct answer 1", "Correct answer 2","Correct answer 3","Correct answer 4","Correct answer 5"};
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();
}
#Override
public void onClick(View view) {
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
if(!alive)
alive = true;
break;
case R.id.button1: //answer_1
if(alive == false)
return;
if(correct(1))
correct++;
break;
case R.id.button2: //answer_2
if(alive == false)
return;
if(correct(2))
correct++;
break;
case R.id.button3: //answer_3
if(alive == false)
return;
if(correct(3))
correct++;
break;
case R.id.button4: //answer_3
if(alive == false)
return;
if(correct(4))
correct++;
break;
default:
break;
}
Game();
}
private boolean correct(int button){
try {
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && aString[0] == answers_correct[i]
|| button == 2 && aString[1] == answers_correct[i]
|| button == 3 && aString[2] == answers_correct[i]
|| button == 4 && aString[3] == answers_correct[i])
return true;
}
}
catch(Exception ex){
System.out.println(ex);
}
return false;
}
private void Game(){
if(i1 > questions.length) //no more questions
return;
main.setText("Next");
try {
String answer_list[][] = {
{answers_correct[i1], "Answer 1-2" , "Answer 1-3" , "Answer 1-4"},
{answers_correct[i1], "Answer 2-2" , "Answer 2-3" , "Answer 2-4"},
{answers_correct[i1], "Answer 3-2" , "Answer 3-3" , "Answer 3-4"},
{answers_correct[i1], "Answer 4-2" , "Answer 4-3" , "Answer 4-4"},
{answers_correct[i1], "Answer 5-2" , "Answer 5-3" , "Answer 5-4"}};
Collections.shuffle(Arrays.asList(answer_list[i1]));
answer_1.setText(answer_list[i1][0]);
answer_2.setText(answer_list[i1][1]);
answer_3.setText(answer_list[i1][2]);
answer_4.setText(answer_list[i1][3]);
aString[0] = answer_list[i1][0];
aString[1] = answer_list[i1][1];
aString[2] = answer_list[i1][2];
aString[3] = answer_list[i1][3];
q_textview.setText(questions[i1]);
}
catch(Exception e){
System.out.println(e);
}
tip.setText(correct);
/*questions = question_list.toArray(new String[question_list.size()]);
answers_correct = answer_list_correct.toArray(new String[answer_list_correct.size()]);
question.setText(questions[i1]);
answer_list_correct.remove(questions[i1]);
question_list.remove(questions[i1]);*/
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("");
/* for(String x : questions) {
for(String y : answers_correct){
answer_list_correct.add(y);
question_list.add(x);
Collections.shuffle(answer_list_correct);
Collections.shuffle(question_list);
}
} */
}
}
Best regards.
In Game(), you check i1 > questions.length at the top, but try q_textview.setText(questions[i1]); near the bottom. If i1 == questions.length, that would throw an ArrayIndexOutOfBoundsException (hope I remembered the name correctly), make it i1 >= questions.length. Also, you use i1 as index for answers_correct and answer_list, that won't be out of bounds for the pasted questions and answers_correct, but might be for the real (unlikely, though, you won't have more questions than answers, would you?).
In correct, your if statement
if(button == 1 && aString[0] == answers_correct[i]
|| button == 2 && aString[1] == answers_correct[i]
|| button == 3 && aString[2] == answers_correct[i]
|| button == 4 && aString[3] == answers_correct[i])
return true;
could be shortened to
if (aString[button-1] == answers_correct[i]) return true;
(unless button can have values < 1 or > 4, then you would need to check for button >= 1 && button <= 4 too). However, using == to compare Strings is dangerous and almost certainly wrong. == compares the equality of references, so string1 == string2 is true only if both refer to the same String instance. If, as seems to be the case, all your Strings come from string literals in the source code, it will kind of work because then there is only one instance for each literal, but if outside Strings could enter the game, you must use equals to compare Strings. Use equals also in those cases where == would (sort of accidentally) work.

Categories