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)
Related
I am making an android Hashikawekero puzzle game, I have implemented a algorithm to spawn nodes (Islands) at random positions using a 2-d array this works fine it creates the node at random position but most of the times the map cant be solved. The map nodes spawn at random.
BoardCreation.java Class - this generates the map.
package Island_and_Bridges.Hashi;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import java.util.Random;
import static junit.framework.Assert.*;
//This class Creates the map by random using a 2d array
public class BoardCreation {
// This class member is used for random initialization purposes.
static private final Random random = new Random();
// The difficulty levels.
private static final int EASY = 0;
static public final int MEDIUM = 1;
static public final int HARD = 2;
static public final int EMPTY = 0;
private static int ConnectionFingerprint(BoardElement start, BoardElement end) {
int x = start.row * 100 + start.col;
int y = end.row * 100 + end.col;
// Swap to get always the same fingerprint independent whether we are called
// start-end or end-start
if (x > y ) {
int temp = x;
x = y;
y = temp;
}
Log.d("", String.format("%d %d" , x ,y));
return x ^ y;
}
public class State {
// The elements of the board are stored in this array.
// A value defined by "EMPTY" means that its not set yet.
public BoardElement [][] board_elements = null;
public int [][] cell_occupied = null;
// The width of the board. We only assume squared boards.
public int board_width=0;
public State(int width) {
board_width = width;
board_elements = new BoardElement[width][width];
cell_occupied = new int[width][width];
}
public State CloneWithoutConnections() {
State newstate = new State(board_width);
if (board_elements != null) {
newstate.board_elements = new BoardElement[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
for (int j = 0; j < board_elements.length; ++j) {
if (board_elements[i][j] == null)
continue;
newstate.board_elements[i][j] = board_elements[i][j].clone();
}
}
}
if (cell_occupied != null) {
assert board_elements != null;
newstate.cell_occupied = new int[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
System.arraycopy(cell_occupied[i], 0, newstate.cell_occupied[i], 0, board_elements.length);
}
}
return newstate;
}
public void AddToBridgeCache(BoardElement first, BoardElement second) {
if (first == null || second == null) { return; }
final int fingerprint = ConnectionFingerprint(first, second);
Log.d(getClass().getName(),
String.format("Fingerprint of this bridge %d", fingerprint));
// mark the end points as occupied.
cell_occupied[first.row][first.col] = fingerprint;
cell_occupied[second.row][second.col] = fingerprint;
int dcol = second.col - first.col;
int drow = second.row - first.row;
if (first.row == second.row) {
for (int i = (int) (first.col + Math.signum(dcol)); i != second.col; i += Math.signum(dcol)) {
cell_occupied[first.row][i] = fingerprint;
String.format("deleting bridge");
}
} else {
assert first.col == second.col;
for (int i = (int) (first.row + Math.signum(drow)); i != second.row; i+= Math.signum(drow)) {
cell_occupied[i][first.col] = fingerprint;
}
}
}
} // end of state
private State current_state, old_state;
static private final int WIDTH_EASY = 7;
private void NewGame(int hardness) {
switch(hardness) {
case EASY:
Log.d(getClass().getName(), "Initializing new easy game");
InitializeEasy();
old_state = getCurrentState().CloneWithoutConnections();
break;
}
}
public void ResetGame() {
if (old_state != null) {
Log.d(getClass().getName(), "Setting board_elements to old_elements");
setCurrentState(old_state.CloneWithoutConnections());
} else {
Log.d(getClass().getName(), "old_lements are zero");
}
}
public BoardCreation(int hardness) {
NewGame(hardness);
}
public boolean TryAddNewBridge(BoardElement start, BoardElement end, int count) {
assertEquals(count, 1);
assert (start != null);
assert (end != null);
final int fingerprint = ConnectionFingerprint(start, end);
Log.d(getClass().getName(),
String.format("considering (%d,%d) and (%d,%d)", start.row,start.col, end.row,end.col));
if (start.row == end.row && start.col == end.col) {
Log.d(getClass().getName(), "Same nodes selected!");
return false;
}
assert count > 0;
int dcol = end.col - start.col;
int drow = end.row - start.row;
// It must be a vertical or horizontal bridge:
if (Math.abs(dcol) > 0 && Math.abs(drow) > 0) {
Log.d(getClass().getName(), "not a horizontal or vertical bridge.");
return false;
}
// First we check whether start and end elements can take the specified bridge counts.
int count_start = start.GetCurrentCount();
int count_end = end.GetCurrentCount();
if (count_start + count > start.max_connecting_bridges ||
count_end + count > end.max_connecting_bridges) {
Log.d(getClass().getName(), "This Bridge is not allowed");
return false;
}
Log.d(getClass().getName(),
String.format("Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row, start.col,
count_end, end.row, end.col));
Connection start_connection = null;
Connection end_connection = null;
// Next we check whether we are crossing any lines.
if (start.row == end.row) {
for (int i = (int) (start.col + Math.signum(dcol)); i != end.col; i += Math.signum(dcol)) {
if (getCurrentState().cell_occupied[start.row][i] > 0 &&
getCurrentState().cell_occupied[start.row][i] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
assert start.col != end.col;
if (start.col > end.col) {
start.connecting_east = GetOrCreateConnection(end, start.connecting_east);
end.connecting_west = GetOrCreateConnection(start, end.connecting_west);
start_connection = start.connecting_east;
end_connection = end.connecting_west;
} else {
start.connecting_west = GetOrCreateConnection(end, start.connecting_west);
end.connecting_east = GetOrCreateConnection(start, end.connecting_east);
start_connection = start.connecting_west;
end_connection = end.connecting_east;
}
} else {
assert start.col == end.col;
for (int i = (int) (start.row + Math.signum(drow)); i != end.row ; i += Math.signum(drow)) {
if (getCurrentState().cell_occupied[i][start.col] > 0 &&
getCurrentState().cell_occupied[i][start.col] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
if (start.row > end.row ) {
start.connecting_north = GetOrCreateConnection(end, start.connecting_north);
end.connecting_south = GetOrCreateConnection(start, end.connecting_south);
start_connection = start.connecting_north;
end_connection = end.connecting_south;
} else {
start.connecting_south= GetOrCreateConnection(end, start.connecting_south);
end.connecting_north = GetOrCreateConnection(start, end.connecting_north);
start_connection = start.connecting_south;
end_connection = end.connecting_north;
}
}
start_connection.destination = end;
end_connection.destination = start;
start_connection.second += count;
end_connection.second += count;
getCurrentState().AddToBridgeCache(start, end);
Log.d(getClass().getName(),
String.format("New bridge added. Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row,start.col,
count_end, end.row,end.col));
return true;
}
private Connection GetOrCreateConnection(
BoardElement end,
Connection connection) {
if (connection!= null) { return connection; }
return new Connection();
}
#TargetApi(Build.VERSION_CODES.N)
private void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
setCurrentState(new State(WIDTH_EASY));
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
System.out.println();
}
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
}
private void setCurrentState(State new_state) {
this.current_state = new_state;
}
public State getCurrentState() {
return current_state;
}
}
What algorithm could I use to make sure the Map can be Solved (Islands Connected with Bridges) before spawning the nodes.
This is what the map looks like (don't mind the design)
One thing to consider would be to start with a blank board. Place an island. Then place another island that can be connected to the first one (i.e. on one of the four cardinal directions). Connect the two with a bridge, and increment each island's count.
Now, pick one of the two islands and place another island that it can connect. Add the bridge and increment.
Continue in this way until you've placed the number of islands that you want to place.
The beauty here is that you start with an empty board, and during construction the board is always valid.
You'll have to ensure that you're not crossing bridges when you place new islands, but that's pretty easy to do, since you know where the existing bridges are.
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
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.
First of all, I couldn't find any of my question on google.
This is the following code that I used.
ipAddress = new MaskFormatter("###.###.###.###");
JTextField txtAddress = new JFormattedTextField(ipAddress);
But the code above gives user to (must) input exactly 12 characters.
How to make the JTextField can be written as "12.10.25.25" ?
I would do it differently:
Simply wait for the user to somehow confirm that he has finished entering the address (for example by observing when the field looses focus) and retrieve the value of the field and use one of the many regular expressions that check all properties of valid ip addresses.
Looking at the Oracle tutorial here it seems to me that using a JTextFormattedTextField simply is the wrong answer. That class and the corresponding formats are for either locale-based formatting of dates or numbers.
I think you should be rather looking into input validation; see here for details; and as said; your validation could be based on the things you find here.
Finally: the point is to come up with a consistent user experience. Dont put yourself into a corner by saying: I saw this approach; so I absolutely must use that type of component. Instead, check out the possible options, and go for that one that (given your "budget" of development resources) gives the user the best experience.
Example: instead of using 1 JFormattedTextField, you could go for 4 textfields, and even write code that would move the focus automatically forth and back. Many things are possible; it only depends on how much time you are willing to spend.
My homegrown IP address control based on a single JTextField
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class JIp4AddressInput extends JTextField
{
private final char[] buff = " 0. 0. 0. 0".toCharArray();
private int bpos;
private void putnum (int num, int offset)
{
int a = num/100;
num -= a*100;
int b = num/10;
num -= b*10;
buff[offset] = (char)('0'+a);
buff[offset+1] = (char)('0'+b);
buff[offset+2] = (char)('0'+num);
}
private void align (int base)
{
int end = base+3;
StringBuffer sb = new StringBuffer();
for (int s=base; s<end; s++)
{
if (buff[s] != ' ')
sb.append(buff[s]);
}
while (sb.length() > 1 && sb.charAt(0) == '0')
sb.delete(0,1);
while (sb.length() < 3)
sb.insert(0, ' ');
try
{
int num = Integer.parseInt(sb.toString().trim());
if (num > 255)
sb = new StringBuffer("255");
if (num < 0)
sb = new StringBuffer(" 0");
}
catch (NumberFormatException e)
{
sb = new StringBuffer(" 0");
}
for (int s=base; s<end; s++)
{
buff[s] = sb.charAt(s-base);
}
}
private void alignAll()
{
align(0);
align (4);
align(8);
align (12);
}
private void fwd ()
{
bpos = bpos == 15 ? bpos : bpos +1;
}
private void back ()
{
bpos = bpos == 0 ? bpos : bpos -1;
}
private void backspace()
{
back();
if (bpos == 3 || bpos == 7 || bpos == 11)
{
return;
}
if (bpos < 15)
buff[bpos] = ' ';
}
private void setChar (char c)
{
if (bpos == 3 || bpos == 7 || bpos == 11)
{
fwd();
}
if (bpos < 15)
buff[bpos] = c;
fwd();
}
public JIp4AddressInput()
{
super();
setPreferredSize(new Dimension(110, 30));
setEditable(false);
Action beep = getActionMap().get(DefaultEditorKit.deletePrevCharAction);
beep.setEnabled (false);
setText (new String (buff));
addFocusListener(new FocusListener()
{
#Override
public void focusGained(FocusEvent e)
{
setText (new String (buff));
setCaretPosition(0);
getCaret().setVisible(true);
}
#Override
public void focusLost(FocusEvent e)
{
alignAll();
setText(new String(buff));
}
});
addKeyListener(new KeyAdapter()
{
#Override
public void keyTyped (KeyEvent e)
{
bpos = getCaretPosition();
char c = e.getKeyChar();
if ((c>= '0' && c<= '9') || c == ' ')
{
setChar (c);
}
else if (c == KeyEvent.VK_BACK_SPACE)
{
backspace();
}
else if (c == KeyEvent.VK_ENTER)
{
alignAll();
}
setText(new String(buff));
setCaretPosition(bpos);
}
});
}
////////////////////////////////////////////////////////////////////////////////////////
public InetAddress getAddress()
{
String[] parts = new String(buff).split("\\.");
byte[] adr = new byte[4];
for (int s=0; s<4; s++)
adr[s] = (byte)Integer.parseInt(parts[s].trim());
try {
return InetAddress.getByAddress(adr);
} catch (UnknownHostException e) {
return null;
}
}
public void putAddress (InetAddress in)
{
byte[] adr = in.getAddress();
putnum(adr[0]&0xff, 0);
putnum(adr[1]&0xff, 4);
putnum(adr[2]&0xff, 8);
putnum(adr[3]&0xff, 12);
alignAll();
setText (new String(buff));
}
}
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 */
}