I am developing two separate program which involve method call from each side.Program A is MyNoteCenter.java and program B is SocketServer.java. There consist of a method call in MyNoteCenter to trigger the method in the SocketServer for download the resource, so the counter in SocketServer will increment by 1. when I click the button download inside the MyNoteCenter, it will contact the SocketServer for download request and increment the counter by one if SocketServer receive valid argument but why my counter only rise one time? it will only function well for the first time I click the download button but when I click the second time, the counter still showing 1
This is some portion of my SocketServer program
public String getDownload()
{
int c = 0;
c = c + 1;
switch(software)
{
case "1" :
message = "ITune";
// counter++;
break;
case "2" :
message = "ZoneAlarm";
// counter++;
break;
case "3" :
message = "Winrar";
// counter++;
break;
case "4" :
message = "Audacity";
// counter++;
break;
}
JOptionPane.showMessageDialog(null,"Your download is\n" +message+ "\n the number of download is\n"+c);
return message;
}
This is the method in MyNoteCenter, the method will be trigger after the btn2 is click which is download button, the runCC method will contact the SocketServer method for download
public static void runCC(String software,String id,String name,String job,String country)
{
SocketServer dc = new SocketServer(software,id,name,job,country);
String ServerReplyMessage = dc.getDownload();
JOptionPane.showMessageDialog(null,"Downloading :\n" +ServerReplyMessage);
int answer = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (answer == JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null,"Please click close button");
}
else
{
JOptionPane.showMessageDialog(null,"Please proceed");
}
http://codepad.org/ >>my full SocketServer program
You are re initializing c every time you run the method.
c should be a field defined within the class that will maintain value every time you need to increment it OR evaluate it's current value.
public class MyClass {
private int c = 0;
public String getDownload() {
c++;
switch case...
}
}
Related
So, I am making a turn based combat class in java for when I try to make an rpg. I will provide the code below. I have a public static String called state and a Scanner called sc, and a switch statement for state. Before the switch statement, state = "0". case "0" of the switch statement prints out "A Slime appears\n(1)Attack\n(2)Defend" and makes state = "1".
case "1" has another switch statement in it for sc.nextLine. in this switch statement, case "1" generates damage for me and the slime, subtracts them from our hp, and prints out a message for the attacks, and makes state = "2". case "2" generates the half damage of the slime and prints out a message for the slimes damage, being half what it would be, with you defending inside of attacking and makes state = "2". So, either attack or defend, it makes state = "2". Then for the first switch statement, case "2" prints out the options of attack and defend again and makes state = "1".
When I run the code, it prints the first message sayinjg the slime appears and either attack or defend, but I cant type anything in to console and the code is terminated. I am using Eclipse.
package dfguy;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String state;
public static int cmhp = 40;
public static int cchp = 40;
public static int smhp = 20;
public static int schp;
public static Random dmg = new Random();
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
state = "0";
switch(state) {
case "0":
System.out.println("A Slime appears!\n(1)Attack\n(2)Defend");
schp = smhp;
state = "1";
break;
case "1":
switch(sc.nextLine()) {
case "1":
int cdmg = (dmg.nextInt(6) + 5);
int sdmg = (dmg.nextInt(5) + 4);
System.out.println("You attack the Slime for " + cdmg + "damage!\nThe Slime attacks "
+ "you for " + sdmg + "damage!");
schp = schp - cdmg;
cchp = cchp - sdmg;
state = "2";
break;
case "2":
int sbdmg = (dmg.nextInt(3) + 2);
cchp = cchp - sbdmg;
System.out.println("You defend against attack! The Slme attacks for " + sbdmg + "damage!");
state = "2";
break;
}
break;
case "2":
System.out.println("(1)Attack\n(2)Defend");
state = "1";
break;
}
}
}
There is no loop around the switch to run it more than once - so you go through with state=0, flip it to state=1 and then you're done.
For now you can get away with while(true) { /*your switch*/ } but eventually you probably want while(!dead) { ... }. Also perhaps put your whole switch into a different method rather than doing it all in main.
You are writing a proper state machine, but one key thing about a state machine is that it needs to be called over and over repeatedly. The first time through the state is one thing and later it changes to something else.
The thing is, each state may run over and over. So you have to ask your question in one state, and wait for the response in the next. If you leave it in that state it's just going to keep spamming the question. So state 0 should ask the question, then state 1 just loops waiting for a response and the response sends you to state 2 or 3 for more text.
Or you can even have state machines within state machines. The point is that looping code keeps reaching the same point until it's time to do something else.
The whole thing has to be inside a while loop. You can use while(true) or while(1), or even for(;;) but I like to have a boolean value that I can use so that if I ever want to end the program I can just set it to false and the program ends.
Pseudo-code:
boolean running = true;
while(running){
switch(state){
// etc. etc. for the state machine.
// if you want to end the program somewhere then set running to false
}
}
I am building a simple game of 21. Everything comes together okay, but when I click on the Button that I have assigned to my 'Stand' function, none of the if-statement blocks trigger event though I am meeting conditions of one or the other depending on what cards have already been dealt. I have tested all variations of the statements and I want to have some insight, or a second pair of eyes to see something I do not.
I have tested the function multiple times, and re-written it multiple times. I've tested the function with just that statement present, and it still does not trigger.
This is the function in question:
//when player hits stand button
public void Stand(TextField playerNum, TextField dealerNum, TilePane b, Button hit, Button stand, Button deal, TextField handsLostNum, TextField handsWonNum) {
//obtain current final scores when player stands
playerFinal = Integer.parseInt(playerNum.getText());
dealerFinal = Integer.parseInt(dealerNum.getText());
if (playerFinal > dealerFinal) {
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
playerNum.setText("YOU WIN!");
dealerNum.setText("YOU WIN!");
handsWon += 1;
String temp = Integer.toString(handsWon);
handsWonNum.setText(temp);
}
if (dealerFinal > playerFinal) {
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
playerNum.setText("YOU LOSE!");
dealerNum.setText("YOU LOSE!");
handsLost += 1;
String temp = Integer.toString(handsLost);
handsLostNum.setText(temp);
}
if (dealerFinal == playerFinal) {
playerNum.setText("DRAW! PLAY AGAIN!");
dealerNum.setText("DRAW! PLAY AGAIN!");
hit.setVisible(false);
stand.setVisible(false);
deal.setVisible(true);
}
handsWon = 0;
handsLost = 0;
} //END STAND METHOD
And the condition that helps to meet it is here:
//method to add scores to text fields
public void addScores(int pScore, int dScore, TextField playerNum, TextField dealerNum) {
//ADD PLAYER SCORE
String playerScore = playerNum.getText();
int playerCurrent = Integer.parseInt(playerScore);
int newCurrent = playerCurrent + dScore;
String newScore = Integer.toString(newCurrent);
playerNum.setText(newScore);
//ADD DEALER SCORE
String dealerScore = dealerNum.getText();
int dealerCurrent = Integer.parseInt(dealerScore);
int newDealCurrent = dealerCurrent + pScore;
String newDealScore = Integer.toString(newDealCurrent);
dealerNum.setText(newDealScore);
}
I add the scores to text fields and then pull them again later in the project. Yet, even when the values are meeting the conditions of being larger than the opponents value, the statement does not trigger.
The expected result is when I click on the 'Stand' button, the statement is triggered and then the variable that adds to the total tally is activated.
Try putting System.out in every step to check if it is actually getting there. Put one as the first statement in the Stand method like: System.out.println("In Stand method");
Then put more of those before the if statements and inside them like:
System.out.format("Before: playerFinal : %s, dealerFinal: %s, playerFinal > dealerFinal: %d %n", playerFinal, dealerFinal, playerFinal > dealerFinal);
if (playerFinal > dealerFinal) {
System.out.format("In: playerFinal : %s, dealerFinal: %s, playerFinal > dealerFinal: %d %n", playerFinal, dealerFinal, playerFinal > dealerFinal);
Do that for each of the methods, to see if that method is actually running and what the values are.
If you see that the if statements are executing and the flow going into them, but you don't see any changes on the GUI elements, then try using:
Platform.runLater(() -> {
// Your GUI changes code
playerNum.setText("YOU WIN!");
dealerNum.setText("YOU WIN!");
});
Platform.runLater receives a runnable as an argument, and is the right way to update the GUI if you are using JavaFX.
Sometimes you may save the file and run it and the IDE would not actually compile it, running the old code. In that case, you can try restarting the IDE and trying again.
I am trying to get the names of all selected JRadioButtons from my graphics interface. As such I create the allFacilities array in which I include all of my JRadioButtons.
The first for loop serves to find the number of selected radio buttons.
The second for loop aspires to get the name of each selected button.
When checking what the .getName() returns:
System.out.println("A##" + button.getName());, only null is returned for all cases.
Here is my code:
JRadioButton[] allFacilities = {restaurant, laundry, parking};
int selectedFacilitiesCounter = 0;
for(JRadioButton check : allFacilities) {
if(check.isSelected()) {
selectedFacilitiesCounter += 1;
}
}
String[] selectedFacilities = new String[selectedFacilitiesCounter];
int index = 0;
for(JRadioButton button : allFacilities) {
if(button.isSelected()) {
System.out.println("A##" + button.getName());
switch(button.getName()) {
case "restaurant":
selectedFacilities[index] = "restaurant";
break;
case "laundry":
selectedFacilities[index] = "laundry";
break;
case "parking":
selectedFacilities[index] = "parking";
break;
default:
System.out.println("Facility Not Found");
}
index += 1;
}
}
Does anybody have any ideas on how I can solve my problem?
I believe that what you want is this:
JRadioButton button = new JRadioButton("test");
System.out.println(button.getText());
Which will print test.
The method getName retrieves the name of the component, which you should've set with setName, which I believe you didn't.
I have a simple fact app that has an array of different facts.
I have a next, previous, and home button.
When the home button is pressed, I want the first fact to be displayed again, and after, it will start incrementing again from the first array value.
My home button is not working. If I hit the next button 5 times, then hit the home button, I will be directed to the first fact, but if I hit the next button, then the 6th fact will display, not the second.
Here is my code:
public String nextFact() {
i++;
if(i >= facts.length) {
i = 0;
}
return facts[i];
}
public String previousFact() {
i--;
if(i < 0) {
i = facts.length - 1;
}
return facts[i];
}
public String homeButton() {
int i = 0;
return facts[i];
}
You are declaring a new local version of i.
It should be:
public String homeButton() {
i = 0;
return facts[i];
}
According to your code, I am assuming i is a variable shared across the three methods, which keeps track of the index of the question currently displayed. If that is the case, your method should reset the class member i to 0, instead of creating a local variable.
public String homeButton() {
i = 0;
return facts[i];
}
This should do the trick.
At the moment , when I hit F or f :
private static final char FILL_POLYGON_LOWERCASE = 'f';
private static final char FILL_POLYGON = 'F';
#Override
public void keyTyped(KeyEvent keyEvent)
{
PolygonFiller polyFiller = new PolygonFiller();
char key = keyEvent.getKeyChar();
switch(key)
{
/**
* Fill the polygons
*/
case FILL_POLYGON:
{
if (greenLightForFilling == true)
{
fillPolygon(polyFiller);
System.out.print("called");
}
break;
} // end FILL_POLYGON
case FILL_POLYGON_LOWERCASE:
{
if (greenLightForFilling == true)
{
fillPolygon(polyFiller);
}
break;
}
...
}
The program goes into fillPolygon(polyFiller); .
Meaning , when I hit for the first time f , I go into fillPolygon() .
How can I go into some other method , for example other() , when I hit f or F again ?
Thanks
So the thing is, if you click f/F you goto fill polygon, and pressing f/F again will call other().
This can be a classic case of Stateful Class.
Have an attribute in this at class level.
And on entering f/F check the value and increment it by one.
And on entering f/F again, check the value and increment it by one.
Before each increment you should check whether,
//Am assuming that there are more than two functions, else could use boolean
if (value == 1) {
fillpolygon();
}
else if (value == 2) {
other();
}
else if (value == 2) {
some_other();
}
Remember the entry point will be a single function, from there the flow is delegated based on checks similar to this.
Hope this helps.
Store the previously used button in a variable like 'currentCommand' and 'previousCommand'. Everytime you detect a new input you put current to previous and store the new one in the current member.
Or maybe if you want more than the last two key pressed use a stack.
How can I go into some other method, for example other(), when I hit f or F again ?
You need to introduce a boolean flag.
This is a very simple example of a state machine.