I am trying to build a copy cat of the game risk. I have a while loop which says while the attack isn't finished do something. Then I ask the user to type in either 'end turn' to end turn or 'continue' to recursively call the attack function again. The problem is after the user types in attack a few times and then 'end turn' the turn doesn't end rather it starts from the beginning or the function again. I would greatly appreciate an expert eye to look at my code and see what I am missing, thanks in advance.
public void attackOrSkip(Player player,Player[] playerArray, int playerId) {
boolean attackFinished = false;
int numUnitsAttackWith = 0;
int defenceArmiesNumber =0;
displayString(makeLongName(player) + ": Type 'attack' to attack or 'skip' to skip your turn...");
String command = commandPanel.getCommand();
displayString(PROMPT + command);
if(command.equals("skip") ||command.equals("skip ") ||command.equals("s")) {
return;
}else if (command.equals("attack") ||command.equals("attack ")){
displayString(PROMPT + command);
//while the attack isn't finished
while(attackFinished == false) {
//get the country the user is attacking
int countryAttackingFrom=countryFromCheck(playerId,player);
//get the country to attack
int countryToAttack = countryToCheck(player);
//get the player who we are attacking
int occupierPlayer =board.getOccupier(countryToAttack);
if ((board.getNumUnits(countryAttackingFrom)) < 2) {
displayString("You dont have enough units on this country to make an attack!");
attackOrSkip(player, playerArray, playerId);
break;
}
//if the country is adjacent to another one then you can attack else no
else if(isAdjacent(countryAttackingFrom,countryToAttack)) {
//check the number of unit to attack with
numUnitsAttackWith =numUnitsCheckerAttack(player,countryAttackingFrom);
//check the number of unit to defend with
defenceArmiesNumber = numUnitsCheckerDefence(player,countryToAttack);
//roll the dice
player.rollDice(numUnitsAttackWith);
playerArray[occupierPlayer].rollDice(defenceArmiesNumber);
//display the roll results
displayString(makeLongName(player) + "Rolled: "+printDie(player));
displayString(makeLongName(playerArray[occupierPlayer]) + "Rolled: "+printDie(playerArray[occupierPlayer]));
}
displayString(makeLongName(player) + ": 'end turn' or 'continue'");
command = commandPanel.getCommand();
displayString(PROMPT + command);
if(command.equals("end turn")||command.equals("end turn ") ||command.equals("endturn")||command.equals("endturn ") ||command.equals("end")) {
attackFinished = true;
return;
}else if(command.equals("attack") ||command.equals("attack ")){
// break;
}else if(command.equals("continue") ||command.equals("continue ") ||command.equals("con")){
attackOrSkip(player,playerArray,playerId);
}else {
return;
}
}else {
displayString(makeLongName(player) + ": ERROR, not adjacent countries");
}
}
}
}
Okay - as currently written - every time you call attackOrSkip within the method - you end up 1 level lower in the stack - with a new set of variables -
attackFinished, numUnitsAttackWith, defenceArmiesNumber
When you leave the recursion (i.e. via a return) you end up with simple variables as they were before you enter the recursive call - remember Java is Call By Value (even though you can pass in references to objects, you get a value (the current value of the variable reference when called ... and changing the reference to point at a different object doesn't change the callers reference).
SO, without looking to see whether you have done the correct algorithm - I would guess that if you made the method return type a boolean and returned the status instead of nothing, you could update attackFinished and the right thing might happen..
e.g. change all the
return;
to
return attackFinished;
AND change all the places where you call
attackOrSkip(....)
to set attack finished based on what the method return
attackFinished = attackOrSkip(....)
OR - you can pass in an extra parameter - attackFinished - in a Holder (an example of the concept) object - again the reference can't change, but you can go attackFinished.value = true (and it will then be the same the whole way out the stack as you drop out of the recursion).
A week ago, for a week I tried to have an app I'm making completely independent detecting call states. I'm on Lollipop 5.1, so I can't use PRECISE_CALL_STATE that exists from Marshmallow upwards. I'm restricted to the usual CALL_STATE_RINGING, OFFHOOK and IDLE.
My extensive research (majority here on StackOverflow) with Google's help made me realize there's possibly no other way of detecting call states without these 3 on Lollipop or lower, or without system permissions on newer Android versions. There are very precise call states on all firmwares. But from a thread here on SO, it seems they can only be used by the current phone app (which I won't replace - will still be the normal Phone app). So no way to use those states in this case, it seems.
I'm also writing this question and answering it right away because I was able to make something which works just fine for me with the app I'm making. If it were a phone app, it would have to be more precise though. But in my case, I don't mind at all.
And as I see so many questions about parts of this question, I decided to put it all in the same question and answer it with something I tried to do and went well enough for me, and hopefully for some others. Feel free to suggest improvements and/or post other solutions!
If I did anything wrong on asking and answering right away please correct me. I never did this before.
With what I wrote on the question in mind, I was forced to use these 3 states, or use the call history. As I wanted the app to be as independent as possible, I tried to make the app detect the PRECISE_CALL_STATEs from itself. Except when there are too many calls. In case they're 3 or more, I must go get the call state of some from the call history (except one case if there are 3 calls, which is explained in the code). I just can't detect calls on hold, sadly.
So far I can detect the following cases:
Incoming call;
Incoming call waiting;
Outgoing call;
Call just lost;
Call lost some time ago;
Call just answered;
Call answered some time ago;
Call just finished;
Call finished some time ago.
And this is the code which I made to make this happen. By the way, as this has some lines already and I found out Stack Exchange network websites have an automatic license, then add this one to it (as I say in my profile), so anyone can do whatever they want with it, including copy-pasting (may or may not take time to understand, since when I did this first without comments, I had a hard time understanding what I had done):
This work marked with CC0 1.0 Universal. To view a copy of this
license, visit https://creativecommons.org/publicdomain/zero/1.0
Hope this is big enough to worry about license issues. Saw about this a week ago and I've began to think when to put license notice of CC0 on code I post. If it's not necessary here, please tell me so I can improve the "detection" next times.
public static final String CALL_PHASE_OUTGOING = "CALL_PHASE_OUTGOING";
public static final String CALL_PHASE_RINGING_NEW = "CALL_PHASE_RINGING_NEW";
public static final String CALL_PHASE_LOST = "CALL_PHASE_LOST";
public static final String CALL_PHASE_LOST_LATE = "CALL_PHASE_LOST_LATE";
public static final String CALL_PHASE_RINGING_WAITING = "CALL_PHASE_RINGING_WAITING";
//public static final String CALL_PHASE_ON_HOLD = "CALL_PHASE_ON_HOLD";
public static final String CALL_PHASE_ANSWERED = "CALL_PHASE_ANSWERED";
public static final String CALL_PHASE_ANSWERED_LATE = "CALL_PHASE_ANSWERED_LATE";
public static final String CALL_PHASE_FINISHED = "CALL_PHASE_FINISHED";
public static final String CALL_PHASE_FINISHED_LATE = "CALL_PHASE_FINISHED_LATE";
public static final String BETTER_CALL_STATE_OUTGOING = "BETTER_CALL_STATE_OUTGOING";
public static final String BETTER_CALL_STATE_INCOMING = "BETTER_CALL_STATE_INCOMING";
public static final String BETTER_CALL_STATE_WAITING = "BETTER_CALL_STATE_WAITING";
public static final String BETTER_CALL_STATE_DISCONNECTED = "BETTER_CALL_STATE_FINISHED";
//public static final String BETTER_CALL_STATE_ON_HOLD = "BETTER_CALL_STATE_ON_HOLD";
public static final String BETTER_CALL_STATE_ACTIVE = "BETTER_CALL_STATE_ACTIVE";
/**
* <p>This gets the phase of the call when a new phone state is detected (RINGING, OFFHOOK, or IDLE).</p>
* <p>There are values ending in "_LATE". Those are so because they're only detected after the end of all calls are over and after the phone gets to IDLE state.
* Which means, they already happened some time ago (1 second, 10 minutes, unpredictable).</p>
* <br>
* <p><b><u>---CONSTANTS---</u></b></p>
* <p>- <u>CALL_PHASE_OUTGOING [int]</u> --> returned in case an outgoing call was just started (whether it is answered or not by the other party - it's not possible to detect that easily).</p>
* <p>- <u>CALL_PHASE_RINGING_NEW [int]</u> --> returned in case it's a new incoming call.</p>
* <p>- <u>CALL_PHASE_LOST [int]</u> --> returned in case the call has just been lost.</p>
* <p>- <u>CALL_PHASE_LOST_LATE [int]</u> --> returned in case the call was lost some time ago already.</p>
* <p>- <u>CALL_PHASE_RINGING_WAITING [int]</u> --> returned in case there's a new call which is waiting to be answered (some call is already active).</p>
* <p>- <u>CALL_PHASE_ANSWERED [int]</u> --> returned in case the call has just been answered.</p>
* <p>- <u>CALL_PHASE_ANSWERED_LATE [int]</u> --> returned in case the call was answered some time ago alreaedy.</p>
* <p>- <u>CALL_PHASE_FINISHED [int]</u> --> returned in case the call was just finished (after having been answered - if it wasn't answered, it was LOST or LOST_LATE).</p>
* <p>- <u>CALL_PHASE_FINISHED_LATE [int]</u> --> returned in case the call was finished some time ago already (the same in parenthesis for FINISHED applies here).</p>
* <p><b><u>---CONSTANTS---</u></b></p>
*
* #param context <u>[Context]</u> --> Context of the application.
* #param state <u>[int]</u> --> One of the CALL_STATE in TelephonyManager.
* #param incomingNumber <u>[String]</u> --> Phone number that came with the state change.
* #param calls_state <u>[ArrayList(ArrayList(String))]</u> --> An ArrayList of the indicated type that will have the list of calls currently in processing
* (put empty in the beginning and keep the object where the array was created in memory, so the contents of the array are kept, or save it somewhere,
* but don't give always an empty one - this method handles cleaning it when needed. Just give it empty in the beginning of the app and let the method
* handle it from there).
* #param map_CallLog_to_CALL_PHASE <u>[LinkedHashMap(Integer, String)]</u> --> A map with the TYPEs in CallLog.Call on its keys, and on its valus, the corresponding CALL_PHASEs.
* Example: <br><br>map_CallLog_to_CALL_PHASE.put(CallLog.Calls.INCOMING_TYPE, CALL_PHASE_ANSWERED);
* <br>map_CallLog_to_CALL_PHASE.put(CallLog.Calls.MISSED_TYPE, CALL_PHASE_LOST).
*
* #return <u>[ String[][] ]</u> --> A double array of Strings in which each element contains the number and the phase call (CALL_PHASE) in which the number is currently in.
* There can be more than one event in a state change. It may be understood that a call had already been finished some time ago, or lost some time ago.
* Though, the events will always be in the actual event order. If a call was lost before another was answered, then the order will be exactly that one and not the opposite.
*/
public static String[][] get_call_phase(Context context, int state, String incomingNumber, ArrayList<ArrayList<String>> calls_state, LinkedHashMap<Integer, String> map_CallLog_to_CALL_PHASE) {
switch (state) {
case (CALL_STATE_RINGING): {
//System.out.println("RINGING - " + incomingNumber);
// New incoming call (there are no calls in the current processing call list).
if (calls_state.size() == 0) { // Which means, was in IDLE.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(incomingNumber);
arrayList.add(BETTER_CALL_STATE_INCOMING);
calls_state.add(arrayList);
System.out.println(CALL_PHASE_RINGING_NEW + " -> " + incomingNumber);
return new String[][]{new String[]{incomingNumber, CALL_PHASE_RINGING_NEW}};
} else {
// New incoming call waiting
for (int i = 0; i < calls_state.size(); i++) {
if (calls_state.get(i).get(1).equals(BETTER_CALL_STATE_ACTIVE)) {
// If any call was already active and another one came, then that other one is waiting to be answered.
// This also works with 3 calls, even on case 8, since the state of the 1st call only changes on IDLE.
// Until then it remains ACTIVE, even having been already disconnected (don't know a way to detect it was disconnected).
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(incomingNumber);
arrayList.add(BETTER_CALL_STATE_WAITING);
calls_state.add(arrayList);
System.out.println(CALL_PHASE_RINGING_WAITING + " -> " + incomingNumber);
return new String[][]{new String[]{incomingNumber, CALL_PHASE_RINGING_WAITING}};
//break;
}
}
}
break;
}
case (CALL_STATE_OFFHOOK): {
//System.out.println("OFFHOOK - " + incomingNumber);
String[] to_return = null;
/*if (calls_state.size() == 0) {
// If there are no calls in processing (for example, the app was started with at least one call already in course), abort and do nothing at all.
// Can't have this here... Or it won't detect an outgoing call, which puts the phone in this state in the beginning.
break;
}*/
// Check if it's an outgoing call.
if (calls_state.size() == 0) { // Ou seja, estava em IDLE.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(incomingNumber);
arrayList.add(BETTER_CALL_STATE_OUTGOING);
calls_state.add(arrayList);
System.out.println(CALL_PHASE_OUTGOING + " -> " + incomingNumber);
to_return = new String[]{incomingNumber, CALL_PHASE_OUTGOING};
} else {
// Check if the 1st or only call was answered.
for (int i = 0; i < calls_state.size(); i++) {
if (PhoneNumberUtils.compareStrictly(calls_state.get(i).get(0), incomingNumber)) {
if (calls_state.get(i).get(1).equals(BETTER_CALL_STATE_INCOMING)) {
// If the number was in INCOMING (not WAITING, because I don't know how to detect a call waiting that is answered)
// and we are now in the OFFHOOK state, then the call was answered.
calls_state.get(i).set(1, BETTER_CALL_STATE_ACTIVE);
System.out.println(CALL_PHASE_ANSWERED + " -> " + incomingNumber);
return new String[][]{new String[]{incomingNumber, CALL_PHASE_ANSWERED}};
}
}
}
}
// Add the number to the list with the state OFFHOOK, or update the state in case the number is already on the list.
// This is for in case the cases above don't apply --> WAITING to OFFHOOK (don't know what to do with that - can't be rejected or answered).
// Then in that case, I leave the state CALL_STATE_OFFHOOK on the list.
for (int i = 0; i < calls_state.size(); i++) {
if (PhoneNumberUtils.compareStrictly(calls_state.get(i).get(0), incomingNumber)) {
calls_state.get(i).set(1, String.valueOf(CALL_STATE_OFFHOOK));
break;
}
}
return new String[][]{to_return};
//break;
}
case (CALL_STATE_IDLE): {
//System.out.println("IDLE - " + incomingNumber);
ArrayList<String[]> final_return = new ArrayList<>();
if (calls_state.size() == 0) {
// If there are no calls in processing (for example, the app was started with at least one call already in course), abort and do nothing at all.
break;
}
System.out.println("Aqui:");
for (int i = 0; i < calls_state.size(); i++) {
System.out.println(calls_state.get(i).get(0) + " | " + calls_state.get(i).get(1));
}
//////////////////////////////////////
// Beginning of the LATE events
// We begin by the LATE events for the correct order to go inthe return array of all events, the closes to reality possible.
// Bellow is the handling of all numbers that didn't came with the state IDLE. Only one can come with the state and is the one for which the call was finished right now or lost right now.
// The other would get no treatment. Therefore, this tried to understand what may have happened. All here will be of the LATE type because of exactly that (what happened --> past).
// If it's more than a call, we can apply a "trick" to know the state of the first and of the last - answered or lost. This is an example of the cases 1 and 6 (2 calls) and 7 to 10 (3 calls).
if (calls_state.size() > 1) {
// If the first call would have been lost, this would have gone to IDLE directly, and the list would have gotten empty. Then the call coming next would
// be the first call again. If there is a 2nd, the 1st must have been answered. And if it was answered, it was finished in some moment.
// In case the 1st call wasn't the one that came in IDLE, then it was finished some time ago already.
if (!calls_state.get(0).get(0).equals(incomingNumber)) {
// In 2 calls, if the 2nd comes on IDLE, then it means the 1st one was already finished a some time ago (because, again, if the 1st wasn't answered,
// there would be no 2nd). And this sets that state in the call and returns it.
// This can be applied for 3 or more calls too. In that case, if any call not the 1st gets on IDLE, the 1st was already finished some time ago.
System.out.println(CALL_PHASE_FINISHED_LATE + " -> " + calls_state.get(0).get(0));
final_return.add(new String[]{calls_state.get(0).get(0), CALL_PHASE_FINISHED_LATE});
calls_state.get(0).set(1, BETTER_CALL_STATE_DISCONNECTED);
}
}
for (int i = 0; i < calls_state.size(); i++) {
if (PhoneNumberUtils.compareStrictly(calls_state.get(i).get(0), incomingNumber)) {
if (!(calls_state.get(i).get(1).equals(BETTER_CALL_STATE_INCOMING) || calls_state.get(i).get(1).equals(BETTER_CALL_STATE_WAITING))) {
// In case the call didn't come from INCOMING or WAITING, then check if it was answered some time ago or not.
// Which means, if it wasn't detected the call was answered in the right moment (so it's not in ACTIVE state)...
if (!calls_state.get(i).get(1).equals(BETTER_CALL_STATE_ACTIVE)) {
System.out.println(CALL_PHASE_ANSWERED_LATE + " -> " + calls_state.get(i).get(0));
final_return.add(new String[]{calls_state.get(i).get(0), CALL_PHASE_ANSWERED_LATE}); // ... then it was answered some time ago already.
}
}
break;
}
}
// For 3 or more calls, for all calls in the middle of the 1st and last, it's not possible to know their state without, at least, a way of knowing if any
// ended in the middle or not. There, it would be possible to know that the 2nd one was answered, for example (in the case of 3 calls). But without that,
// there's no way of knowing.
// So, in that case, for the remaining calls, we're forced to go to the phone's call history.
// This unless the case 9 happens. In that case, we can know the state of the 3 calls.
// Sum up: this is done for all calls, except the 1st and last, and the one that got to IDLE. Supposing it's the 2nd in the case of 3 calls, nothing it's done.
// In other cases, the calls that get here, we got get the state from the call history.
// And this is done here to go in the correct order in the return array. After the handling of the 1st call and before the handling of the last call. And on the LATE events.
if (calls_state.size() >= 3) {
for (int i = 1; i < calls_state.size()-1; i++) {
if (calls_state.get(i).get(0).equals(incomingNumber)) {
continue;
}
int tipo_chamada = obter_tipo_ultima_chamada_numero(context, calls_state.get(i).get(0));
if (tipo_chamada == CallLog.Calls.INCOMING_TYPE || tipo_chamada == CallLog.Calls.MISSED_TYPE) {
System.out.println(map_CallLog_to_CALL_PHASE.get(tipo_chamada) + " -> " + calls_state.get(calls_state.size() - 1).get(0));
final_return.add(new String[]{calls_state.get(calls_state.size() - 1).get(0), map_CallLog_to_CALL_PHASE.get(tipo_chamada)});
}
calls_state.get(calls_state.size() - 1).set(1, BETTER_CALL_STATE_DISCONNECTED);
}
// TODO Imagine the same person calls, gives up, calls again, I hang up who I was talking with and answered this person.
// This will detect the state as the last one (answered), when I didn't answered the 1st time.
// This should be in real-time detecting the exact states from the call history if it can't get them directly, but I don't have time to think on that.
// In the app I'm making (an assistant), I don't need all the states when the happen exactly. Only missed calls in the end and inoming calls in the beginning.
}
if (calls_state.size() > 1 && !calls_state.get(calls_state.size() - 1).get(0).equals(incomingNumber)) {
// The detection of the last call, in case it was lost some time ago, works both for 2 as for any other superior number of calls.
// For only one call it's not necessary, because on that case, we know exactly when it's lost.
// PS: The call that got to IDLE is never LOST_LATE - either lost right now or finished right now.
// If the last call on the list got the OFFHOOK state (which means, without knowing if it was answered or lost in the right moment),
// and didn't get here on IDLE, then by the cases 1 and 6 for 2 calls, and by the cases 7 to 10 for 3 calls, it wasn't answered either,
// or it would have been that call getting to IDLE itself.
// Getting the 1st one here on IDLE in the case of 2 calls or any other call in the case of 3 calls, then this last one was lost some time ago.
if (calls_state.get(calls_state.size() - 1).get(1).equals(String.valueOf(CALL_STATE_OFFHOOK))) {
System.out.println(CALL_PHASE_LOST_LATE + " -> " + calls_state.get(calls_state.size() - 1).get(0));
final_return.add(new String[]{calls_state.get(calls_state.size() - 1).get(0), CALL_PHASE_LOST_LATE});
calls_state.get(calls_state.size() - 1).set(1, BETTER_CALL_STATE_DISCONNECTED);
}
}
// End of LATE events
//////////////////////////////////////
// Now processing of the immediate events, so they get all in order (the late ones happened before the immediate ones).
for (int i = 0; i < calls_state.size(); i++) {
if (PhoneNumberUtils.compareStrictly(calls_state.get(i).get(0), incomingNumber)) {
if (calls_state.get(i).get(1).equals(BETTER_CALL_STATE_INCOMING) || calls_state.get(i).get(1).equals(BETTER_CALL_STATE_WAITING)) {
// If it came directly from INCOMING or WAITING states to IDLE, then the call was lost right now.
System.out.println(CALL_PHASE_LOST + " -> " + incomingNumber);
final_return.add(new String[]{incomingNumber, CALL_PHASE_LOST});
} else {
// If the state is not INCOMING or WAITING, this in case will be OFFHOOK or ANSWERED. Which means, the call was finished right now (means was alreaedy answered some ago - or would have been lost).
// In no case where a call goes from OFFHOOK to IDLE means the call was lost some time ago, from the testing. So the only option is the call having been finished, or lost, right now (which is handled on the above IF).
System.out.println(CALL_PHASE_FINISHED + " -> " + incomingNumber);
final_return.add(new String[]{incomingNumber, CALL_PHASE_FINISHED});
}
calls_state.get(i).set(1, BETTER_CALL_STATE_DISCONNECTED);
break;
}
}
calls_state.clear();
return final_return.toArray(new String[0][0]);
//break;
}
}
return null;
}
I call this from inside TelephonyManager.listen() method, when the phone state changes. That method I have in a constructor of a class which is instanciated on a service that never stops and it's the main service of the entire app. Basically, this object is always on memory. Read method description there to know what to do with it. Hopefully I explained decently. If I didn't, please tell me what I can explain better.
If anyone has a better solution, please feel free to share! I'd appreciate it! A better way than this one that I see is on every phone state change, go see if there was a change in the call history, depending on which change it was. But that would take even more time from me and I don't have enough for that. A week for this was already too much, since I had to borrow my mother, father and brother's phones, and sometimes the house phone to get to this hahaha. And they're not home all the time.
I'll leave a GitHub link here for the rest of what is needed to understand the code completely. I talk there about case number X and Y, for example. That's here: https://github.com/DADi590/Detect-better-call-states-on-Android, along with ideas that I had and didn't work or that I had but will not implement for lack of time.
I just started learn Java and I'm stuck with this problem: I have an infinite while-loop which creates a message to send over a socket; currently the message is not send until a number of elements is poll from a queue and read them.
String msg = null;
String toSend = "";
String currentNumOfMsg = 0;
String MAX_MSG_TO_SEND = 200;
while(true) {
if ((msg = messageQueue.poll()) != null) { // if there is an element in the list
toSend += (msg + "#");
currentNumOfMsg++;
if (currentNumOfMsg == MAX_MSG_TO_SEND) {
try {
sendMessage(toSend); // send to socket
} finally {
msg = null;
toSend = "";
currentNumOfMsg = 0;
}
}
}
}
My goal is to send the message after N seconds, without waiting to reach the MAX_MSG_TO_SEND... Is it possible to do it or I shall continue with this approach?
While the other answer is perfectly valid, I thought it may be valuable to tell you that ScheduledExecutorService (documentation found here), lets you call a function foo() every n seconds using the method scheduleAtFixedRate().
Basically, the actually setting up the executor is as easy as:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(foo, 0, n, TimeUnit.SECONDS);
I think putting any more code in here is bit unnecessary, but to see how to do this in more detail, look here, here, or here. These links give some basic examples. I would really recommend doing it this way as this class is part of the java util library (so no extra dependencies) and you don't actually have to worry very much about the multithreading/scheduling part of it, it takes care of all that for you. But thats just my $.02.
Leave a question/comment if you have one, I'll try to answer it.
Yeah, definitely you can do such a thing. But at first you should store your receive messages in a data structure and when you want to send the data via the socket, send the data in the data structure.
also, you can use guava stopWatch to send the message exactly on time. for further information, you can see https://dzone.com/articles/guava-stopwatch
Otherwise, you can use a long variable which stores System.currentTimeMillis() and each time checks if the expected elapsed time is received or not like below sample code:
long l = System.currentTimeMillis();
if(System.currentTimeMillis() - l >= 10000) {
//send data
}
I am learning java and so far I have created a password check using if statements. However I inserted my working String check into a while loop and added Thread.sleep(3000); for a 3 second delay, however once I completed that my GUI just keeps lagging and freezing on one page as if the button was pressed. Can somebody please show me how to make a working example of a code with a String check and after a certain amount of tries a delay to stop the user from trying again?
(here is what I have:)
//var declaration
boolean match = false;
String1 = "hi";
String2 = (I know this is not code but just to omit some code:) userInput
int time = 3000;
int attempt = 0;
//check
while(!match && attempt < (maximumTries+1)){
if(String1.equals(String2)){
System.out.print("match");
}
else if(attempt < 11){
attempt++;
System.out.println("Failed:" + attempt);
}
else{
attempt++;
System.out.println("Please try again later you have:" + attempt + "failed attempts");
try{
Thread.sleep(time);
}
catch(InterruptedException ex) {
Logger.getLogger(PasswordEntry.class.getName()).log(Level.SEVERE, null, ex);
}
time = time + 1000;//1 second more every time
}
}
your code is doing an infinite loop once the first attempt does not match.
in each of the iterations of your loop there is no change at all, aside from incrementing the counter. so the counter just increases forever (with some delays in between).
it seems the reasoning behind your code was that String2 got updated with user input inside the loop not outside. This way, on each iteration you would have a different String2 to compare against.
That's your issue, not the way you delay between attempts (that for sure can be improved in any case).
You should avoid using the Thread.sleep option since it completely freezes the main thread. You could also try creating another thread, which will be frozen and later in gives a callback to the main one. For example through a boolean variable. I'd also agree on the timer solution mentioned by BladeMight.
My result
Expected result
public void run () {
try {
handlers.addElement (this);
broadcast("Welcome " + name);
while(handlers.size() != 2){
if(handlers.size() > 2){
this.out.writeUTF ("The Room is full!");
this.out.flush();
handlers.removeElement(this);
socket.close();
}
}
broadcast("No of Player: " + handlers.size());
for(int i = 0; i < handlers.size(); i++){
GameHandler player = (GameHandler) handlers.get(i);
broadcast("Player " + (i + 1) + ": " + player.name);
}
System.out.println("Game starts!");
startGame(4);
....
}
protected static void broadcast (String message) {
synchronized (handlers) {
Enumeration e = handlers.elements ();
while (e.hasMoreElements ()) {
GameHandler handler = (GameHandler) e.nextElement ();
try {
handler.out.writeUTF (message);
handler.out.flush ();
} catch (IOException ex) {
handler.stop ();
}
}
}
}
The problem is the difference between the expected result and my actual result. I have no idea why the broadcast before the while loop runs normally but others run twice
Your problem is that in your case, each of the thread is sending the broadcast. Either you need to have a "master" / "server" of games thread that does the "system announcements" broadcasting, -or- elect one of the client threads (maybe the "player 1" thread?) to send the announcements.
The problem is the difference between the expected result and my actual result. I have no idea why the broadcast before the while loop runs normally but others run twice
You really don't give enough details on your problem but I see these issues:
You talk about TCP and the code mentions sockets but you are processing a local elements collection. Unless you are talking to the same JVM over TCP (which is strange) the elements collection is going to start 2 players on each client. Is that really what you expect?
Even though you says elements is a Vector you still need to synchronize on it at the start of the run() method because you are performing multiple operations on it and there are race conditions. For example, if 3 handlers are added, they will all remove themselves and close their own sockets.
Vector really is an outdated collection. You should be using something else.
When the first thread adds itself to elements it then enters a spin loop waiting for the second person to join the game. Seems like a waste there. Some small Thread.sleep(...) would be appropriate.
If the room is full I suspect that the thread should return; from the run() method. Instead it continues on which I suspect is not good.
Hope something here helps.