When I enter a number within a range in the text field, the boolean should change based on the number typed in. But it still remain false for the one between 10 to 30 and above 30. What am I missing in my code?
Submitbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int value = Integer.valueOf(candynumf.getText());
if(value > 0 && value <= 10)
{
candypackage1 = true;
candypackage2 = false;
candypackage3 = false;
}
else if(value > 10 && value <= 30)
{
candypackage1 = false;
candypackage2 = true;
candypackage3 = false;
}
else if(value > 30)
{
candypackage1 = false;
candypackage2=false;
candypackage3 = true;
}
String candypack = String.valueOf(candypackage1);
candypackage1bl.setText(candypack);
});
Your code is setting the local variable candypackage1 to true, not the field. You then set the text to the field candypackage1. Either move your code for setting text inside the if statement, move the local declaration outside the if statement, or set the field instead of creating a local variable.
Related
Could you please help me find a solution for my code? I'm making a new Android app in which I need to make some calculations and the scenario is the following:
There are four fields to be calculated. Two EditText (number decimal) field are obligatory and the other two are optional, BUT, if the optional fields are filled, then it needs to be in the calculation, otherwise only the obligatory fields will be used.
Right now I'm totally OK with calculating the obligatory fields but when I try some if-else clause to include the optional fields in the calculation, the app goes bananas.
I'm not sure where I should make this two-step option, if I should use boolean to check the option field condition, if I just keep using if-else...
The problem is not the calculatin itself, but having two ways for the code to follow: One using only the obligatory fields if nothing else is inserted and the other one using all four fields.
Thanks everyone!
Code below is only using the two obligatory fields.
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
double valorResultado = valorEtanol / valorGasolina;
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
You almost got it. What happens now, since you have an if-if-elseconstruction, it considers the first if statement to be seperate from the if-else block below. That is to say, if editEtanol.length() == 0 evaluates to false, it will execute the else block below, even if editGasolina.length() == 0 evaluates to true.
Changing the line if (editEtanol.length() == 0) { to else if (editEtanol.length() == 0) { should already help alot. Hope that helps!
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
boolean optionalField1Used = optionalEditText1.length() != 0;
boolean optionalField2Used = optionalEditText2.length() != 0;
double valorResultado = 0;
if (!optionalField1Used && !optionalField2Used) {
valorResultado = valorEtanol / valorGasolina;
} else if (optionalField1Used && !optionalField2Used) {
valorResultado = //some other calculation
} else if (!optionalField1Used && optionalField2Used) {
valorResultado = //yet another calculation
} else {
valorResultado = //calculation if both optional fields used
}
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
Let us assume that the optional fields are called edit1 and edit2. I also assume that in order to use the alternative computation, both optional values must be present.
To enhance code clarity, I would define two Boolean variables to explicitly indicate whether the mandatory and optional fields have values. Something like the following.
public void calcularResultado(View view) {
var mandatoryValues = true;
var optionalValues = false;
if (editGasolina.length() == 0 {
editGasolina.setError("Insira o valor");
mandatoryValues = false;
}
if (editEtanol.length() == 0 {
editEtanol.setError("Insira o valor");
mandatoryValues = false;
}
if (edit1.length() > 0 && edit2.length() > 0) {
optionalValues = true;
}
if (mandatoryValues) {
if (optionalValues) {
// do alternative computation
} else {
// do computation for mandatory values only
}
}
}
Note that if either mandatory value is absent, no computation is performed.
Hope it helps - Carlos
I'm trying to program a bug to move around an array attached to a custom Room object, whilst keeping count of how many times each tile has been stepped on.
The Room object is working properly, as are the movement and the counting. However, the bug's coordinates, bugX and bugY, are somehow reverting to 0 after exiting the nextMove method. Their values only revert when exiting the method; even the last line of code in the nextMove method itself uses their new values.
Relevant portion of the method is attached, but other sections can be added upon request.
if (dirNum == 0 && bugY < length-1) //Move up
bugY++;
else if (dirNum == 1 && bugX < width-1) //Move right
bugX++;
else if (dirNum == 2 && bugY > 0) //Move down
bugY--;
else if (dirNum == 3 && bugX > 0) //Move left
bugX--;
else {
System.out.println("Error: Cannot move " + direction + ".");
canMove = false;
dirNum = generator.nextInt(4);
continue;
}
This is the context for the command itself.
while (endSim == false) {
nextMove(bugX, bugY);
System.out.print(room.printRoom() + "\n\nNext move? (y/n) ");
simSentinel = in.next();
if (simSentinel.charAt(0) == 'n')
endSim = true;
}
The declarations where the starting coordinates are assigned aren't inside any loops, let alone where the variable itself is called.
The problem is the one described by #T.J.Crowder in his answer though applied to java.
Variables passed as parameters in java are passed by value. If the value is changed by the method receiving the parameter, the change only affects the value inside that method. The "outside" value doesn't change.
What you can do is to encapsulate the coords in an object and pass the encapsulating object as a parameter.
Then the method will receive the object by value, and change it's state (instead of the value of the object).
For a deeper understanding see this question
EDIT I:
I cleand up the code a bit. Though it is is missing the declaration of room and simSentinel, if you add that you should have a running example.
public class Bug{
public int x=0;
public int y=0;
}
public class SimpleSim {
private int dirNum = 0;
private int length = 20;
private int width = 20;
private boolean canMove = true;
private Random generator = new Random();
private boolean endSim = false;
public static void main(String [] args) {
SimpleSim simpleSim = new SimpleSim();
simpleSim.start();
}
private void start() {
Bug myBug = new Bug();
// Give the bug some initial x, y values.
myBug.x = 0;
myBug.y = 0;
while (endSim == false) {
nextMove(myBug);
System.out.print(room.printRoom() + "\n\nNext move? (y/n) ");
simSentinel = in.next();
if (simSentinel.charAt(0) == 'n')
endSim = true;
}
}
}
public void nextMove(Bug bug){
if (dirNum == 0 && bug.y < length-1) //Move up
bug.y++;
else if (dirNum == 1 && bug.x < width-1) //Move right
bug.x++;
else if (dirNum == 2 && bug.y > 0) //Move down
bug.y--;
else if (dirNum == 3 && bug.x > 0) //Move left
bug.x--;
else {
System.out.println("Error: Cannot move " + "?" + ".");
canMove = false;
dirNum = generator.nextInt(4);
}
}
}
It seems that you are passing your bugX and bugY parameters by value. In this case, changing their value inside the method won't affect their values outside the method.
You may want to make your nextMove method return the new values for bugX and bugY after they are computed so that you can gather them back into your actual bugX and bugY variables
The first two methods are chunks out of my GUI programme. There are various text fields that allow me input data and then buttons on the GUI take this data and call different methods.
public String getTenant()
{
String theTenant = (tenantsNameText.getText());
return theTenant;
public int getPropertyNumber()
{
int propertyNumber = -1;
try{
propertyNumber = Integer.parseInt(propertyNumberText.getText());
if (properties.size() == 0){
propertyNumber = -1;
}
if (propertyNumber < 0 && propertyNumber >= properties.size()){
propertyNumber = -1;
}
}
catch(NumberFormatException exception){
}
return propertyNumber;
}
In this method I to take the data from the text field of "getTenant" and the data from the text field of "getPropertyNumber". What I'm not sure how to do is check if the property number is -1 or not, and this needs to be verified in the method "addTenant".
public void addTenant()
{
}
I possibly didn't ask the question right, but i figured it out with some help from a colleague.
public void addTenant()
{
int index = getPropertyNumber();
String newTenant = getTenant();
if(index != -1){
Property property = properties.get(index);
if(property instanceof PropertyToLet){
PropertyToLet propertyToLet = (PropertyToLet) property;
propertyToLet.addTenant(newTenant);
}
}
}
I am writing a simple SRMS, and I need to validate the input from the user if it matches some criteria depending on the field, e.g. an email field or a phone field. The app is to run in a featured phone and so I am using the Java ME SDK with a virtual machine for testing.
What is the best way to do so, what would be the best way to validate the input and if the input does not meet some criteria, should the user be notified or the value she has entered to be set to null again.
public void name() {
boolean nameValid = false;
display = Display.getDisplay(this);
nameForm = new Form("Student Record Management (1/4");
TextField firstName = new TextField("First Name(s)", "", 20, TextField.ANY);
TextField lastName = new TextField("Last Name", "", 20, TextField.ANY);
TextField personNumber = new TextField("Person Number", "", 10, TextField.NUMERIC);
back = new Command("BACK", Command.BACK, 1);
next = new Command("Continue", Command.ITEM, 2);
nameForm.append(firstName);
nameForm.append(lastName);
nameForm.append(personNumber);
nameForm.addCommand(back);
nameForm.addCommand(next);
nameForm.setItemStateListener(this);
nameForm.setCommandListener(this);
display.setCurrent(nameForm);
if (firstName.toString().length() > 0) {
nameValid = true;
}
}
The person who started the code has implemented the CommandListener and ItestStateListener.
I am not sure what is the second one does and it has an abstract method to be filled which is called itemStateChanged(Item item) am I supposed to check for changes and validate in here ?
The ItemStateListener notifies the application of changes in Form items. The item itemStateChanged(Item item) method is called when an item in your form is changed by the user or when Item.notifyStateChanged() is called in an Item. The argument is the Item (Textfield, DateField, ect) that changed value.
I would recommend that you call your validation method inside both the CommandAction and ItemStateListener. In the itemStateChanged only the current Item (the one received in the argument) should be checked. In the CommandAction every field should be checked. This way every Item is validated in every situation.
public static boolean validateEmailID(String email) {
email = email.trim();
String reverse = new StringBuffer(email).reverse().toString();
if (email == null || email.length() == 0 || email.indexOf("#") == -1) {
return false;
}
int emailLength = email.length();
int atPosition = email.indexOf("#");
int atDot = reverse.indexOf(".");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLength);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
for (int i = 0; email.length() - 1 > i; i++) {
char i1 = email.charAt(i);
char i2 = email.charAt(i + 1);
if (i1 == '.' && i2 == '.') {
return false;
}
}
if (email.charAt(atPosition - 1) == '.' || email.charAt(0) == '.' || email.charAt(atPosition + 1) == '.' || afterAt.indexOf("#") != -1 || atDot < 2) {
return false;
}
return true;
}
Hello I would like to know. How can I set a variable to true or false and vice versa with a JButton? My first thought would be create the variables like
private boolean value1, value2;
and the buttons like
private JButton toggle1, toggle2;
// see code below
The problem is that it won't react on the button somehow. Is it possible this way or do I have to use something else?
edit: here is the relevant code. ( my ActionListener)
public void actionPerformed(ActionEvent e) {
if( e.getSource() == toggle1 ) {
if(aan1 == false) {
aan1 ^= true;
System.out.println(aan1);
}
else if(aan1 == true) {
aan1 ^= false;
}
}
try {
// controleer of de ingevulde waarde tussen de 0 en de 15 is
if( e.getSource() == burn && Integer.parseInt(textfield.getText()) < 16 && Integer.parseInt(textfield.getText()) > 0) {
// brand kaars
if( height > 15 && aan1 == true) {
int aantal = Integer.parseInt(textfield.getText());
height -= aantal;
}
if( height2 > 15 && aan2 == true) {
int aantal = Integer.parseInt(textfield.getText());
height2 -= aantal;
}
// opnieuw tekenen
repaint();
}
else {
JOptionPane.showMessageDialog(null, "error: vul een getal tussen de 0 en 15 in!"); // alertbox melding
}
}
catch(NumberFormatException error) {
JOptionPane.showMessageDialog(null, "error: een van de velden bevat geen cijfer of is niet ingevuld!"); // alertbox melding
}
}
Not sure exactly what you're asking but to toggle the value of a boolean you can use:
value1 = !value1;
or
value1 ^= true;
Then print your variable:
System.out.println(value1);
As suggested in How to Use Buttons, JToggleButton may be a good choice for this, as the isSelected() predicate reflects the button's state.
state = button.isSelected()
Examples may be found here, here and here.
just do this?:
value1 != value1;
this inverst the current value: so if false, it will change to true, and vice versa.
EDIT:
Should be:
value = !value;
If you want to toggle a boolean variable when pressing a button, you should use a JCheckBox instead of JButton for that purpose which has an internal boolean state and it updates this variable on its own. The check box also makes this boolean state visible to the user.
When you need the boolean variable, you can ask it with the JCheckBox.isSelected() method.