toggle a variable to true/false with a JButton - java

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.

Related

Boolean value didn't change despite input from text field

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.

If-else with two possible ways

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

Java: Listen For Second KeyPress

I have a list of colors with numbers associated with them. I'd like to make it so that, if the user types in "2", it selects "2: Green"; if they type in "21", it selects "21: Yellow"; etc. I'm trying to use KeyPressed, and I think I need some way for the program to listen for the first number pressed and then wait a second to see if another is pressed. For example, something like this:
// The integer pressed will always be zero or positive.
private void jComboBox1KeyPressed(KeyEvent evt) {
int code = -1;
for(int i = 0; i < 10; i++) {
if (evt.getKeyCode() == i) {
if (code == -1) {
code = i;
} else {
code += i;
}
break;
}
}
// PSEUDO-CODE: if (KeyEvent newEvt is pressed within 1 sec) {
jComboBox1KeyPressed(newEvt);
}
}
Then, I suppose I'd have a key-value map with an index and the color numbers, and I'd set the selected item for jComboBox1 based on code (the selected color number).
I've got it working for a single keyPressed:
private void jComboBox1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_0) {
jComboBox1.setSelectedItem("2: Green");
}
else if (evt.getKeyCode() == KeyEvent.VK_1) {
jComboBox1.setSelectedItem("21: Yellow");
}
else if (evt.getKeyCode() == KeyEvent.VK_2) {
jComboBox1.setSelectedItem("13: Blue");
}
else if (evt.getKeyCode() == KeyEvent.VK_3) {
jComboBox1.setSelectedItem("2041: Red");
}
}
Here's the interface:
PLEASE NOTE: This is an example I quickly made and not the actual app I'm creating. My app involves many more number options, but as with this example, the numbers will always be positive.

How can I set an enum with an if-statement or a for-loop?

I want that people can assess themselves. For that they need to enter a number between 0 and 10 (0,1,2,3,4,5,6,7,8,9,10). Depending on their number my enum should switch.
My enum is called "knowlede" and I got four different steps of "knowledge".
0-3 = Beginner // 4-6 = Advanced // 7-9 = Professional // 10 = Master
My idea was to set the users enum level with an if statement and/or a for loop.
This is my code so far, but as you can see I could shorten this code but I don't know how; I read some other threads but for some reason they didn't work or I didnt't get them.
#SuppressLint("SetTextI18n")
public Wissenstand Bestätigung(View v) {
TextView uWissen = (TextView) findViewById(R.id.textView_Wissen_Titel);
TextView pWarung = (TextView) findViewById(R.id.textView_Wissen);
TextView eWissen = (TextView) findViewById(R.id.editText_eingabeWissentsstand);
if ("0".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Beginner;
} else if ("1".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Beginner;
} else if ("2".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Beginner;
} else if ("3".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Beginner;
} else if ("4".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Fortgeschrittener;
} else if ("5".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Fortgeschrittener;
} else if ("6".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Fortgeschrittener;
} else if ("7".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Pro;
} else if ("8".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Pro;
} else if ("9".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.Pro;
} else if ("10".equals(eWissen.getText().toString())) {
knowledge = Wissenstand.GrandMaster;
} else {
uWissen.setText("Fehler gefunden!");
uWissen.getResources().getColor(android.R.color.holo_red_dark);
pWarung.setText("Gib eine Zahl von 0 bis 10 ein!\n0,5-er Schritte sind nicht erlaubt!\nWeitere Informationen kannst du der Legende entnehmen!");
pWarung.getResources().getColor(android.R.color.holo_red_light);
}
return null;
}
If you need some help because u don't understand some words, text me, I'll answer as fast as I can.
The language is "german".
I'd implement that something like this:
enum KnowledgeLevel
{
BEGINNER, ADVANCED, PROFESSIONAL, MASTER;
static KnowledgeLevel fromUserInput(final int input)
{
if (input >= 10) {
return MASTER;
}
else if (input >= 7) {
return PROFESSIONAL;
}
else if (input >= 4) {
return ADVANCED;
}
else {
return BEGINNER;
}
}
}
Example usage would be:
final String input = "5";
KnowledgeLevel level = KnowledgeLevel.fromUserInput( Integer.parseInt(input) );
This has a few advantages over your implementation:
There's less repetition because I used ranges >= rather than explicitly mentioning all integers
It separates the concerns of receiving a user input and converting that to a knowledge level.
It places the mapping of integers to levels in a place where its easily reusable.
You could use a Map which stores the mapping of ratings to enum values:
Map<String, Wissenstand> ratingToWissenstand = new HashMap<>();
ratingToWissenstand.put("0", Wissenstand.Beginner);
ratingToWissenstand.put("1", Wissenstand.Beginner);
ratingToWissenstand.put("2", Wissenstand.Beginner);
ratingToWissenstand.put("3", Wissenstand.Beginner);
ratingToWissenstand.put("4", Wissenstand.Fortgeschrittener);
ratingToWissenstand.put("5", Wissenstand.Fortgeschrittener);
ratingToWissenstand.put("6", Wissenstand.Fortgeschrittener);
ratingToWissenstand.put("7", Wissenstand.Pro);
ratingToWissenstand.put("8", Wissenstand.Pro);
ratingToWissenstand.put("9", Wissenstand.Pro);
ratingToWissenstand.put("10", Wissenstand.GrandMaster);
knowledge = ratingToWissenstand.get(eWissen.getText().toString());
if (knowledge == null) {
// Handle invalid eWissen-text value
}
The map can be made a static field and initialised only once. Then you only have the get-Call in your code.
Try something like this as pseudo code below.
You define an array with all possible answers for knowledge.
Then, you validate option is a number in proper range 1-10.
Finally if selected option is in proiper range, you assign knowledge from array or else condition.
Wissenstand knowledges[] ={ Wissenstand.Beginner,Wissenstand.Beginner,Wissenstand.Beginner,Wissenstand.Beginner,Wissenstand.Fortgeschrittener,Wissenstand.Fortgeschrittener,Wissenstand.Fortgeschrittener,Wissenstand.Pro,Wissenstand.Pro,Wissenstand.GrandMaster};
int option = -1;
try{
option=Integer.getInt(eWissen.getText().toString());
}
catch(Exception e){
}
if (option>0 && option <=knowledge.size()){
knowledge=knowledges[option];
}
else{
uWissen.setText("Fehler gefunden!");
uWissen.getResources().getColor(android.R.color.holo_red_dark);
pWarung.setText("Gib eine Zahl von 0 bis 10 ein!\n0,5-er Schritte sind nicht erlaubt!\nWeitere Informationen kannst du der Legende entnehmen!");
pWarung.getResources().getColor(android.R.color.holo_red_light);
}
int value = Integer.parseInt(eWissen.getText().toString());
if(value < 4){
knowledge = Wissenstand.Beginner;
}else if(value < 7){
knowledge = Wissenstand.Fortgeschrittener;
}else if(value < 10){
knowledge = Wissenstand.Pro;
}else{
knowledge = Wissenstand.GrandMaster;
}

Variables in Methods don't save their value

I'm having a problem with 2 variables, the first of them is called "Num_Viajes" and the function is increasing it value by one everytime I call the method "de_Viaje". The second is called "Total_Pasajeros" and the function is make an addition between itself and another variable called "Num_Pasajeros", both variables are int.
Anyway the thing is, when I call the Method "Reporte_Final" both variable should print their results, for example: If I call the Method "de_Viaje" 2 times and I enter the value "45" for the variable "Num_Pasajeros" the program should return this:
Num_Viajes = 2
Total_Pasajeros = 90
But instead, it returns:
Num_Viajes = 1
Total_Pasajeros = 45
So I think that's because the program is not saving the values of my variables, so they are always restarting. How can I fix this?
Here's the code:
import javax.swing.*;
public class Empresa_Autobuses
{
String Tipo_Vehiculo;
String Analisis_Viaje;
int Num_Pasajeros;
int Num_Viajes;
int Total_Pasajeros;
int Prom_Pasajeros;
public static void main(String ... args)
{
boolean Bandera_Falsa = true;
Empresa_Autobuses Viajero = new Empresa_Autobuses();
do
{
Viajero.de_Viaje();
Viajero.Reporte_Viaje();
Viajero.Solicitud_Viaje();
Viajero.Reporte_Final();
}while(Bandera_Falsa == true);
}
public void de_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
Tipo_Vehiculo = JOptionPane.showInputDialog("Selecciona el Tipo de Autobus (G = Grande, P = Pequeño").toUpperCase();
Num_Pasajeros = Integer.parseInt(JOptionPane.showInputDialog("Introduzca el Número de Pasajeros: "));
if(Tipo_Vehiculo.equals ("G"))
{
if(Num_Pasajeros > 60)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 30)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else if(Tipo_Vehiculo.equals ("P"))
{
if(Num_Pasajeros > 20)
{
JOptionPane.showMessageDialog(null, "¡Se ha superado la Capacidad Máxima del Autobus!");
Viajero.Solicitud_Viaje();
}
else if(Num_Pasajeros >= 10)
{
Analisis_Viaje = "Ganancia";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
else
{
Analisis_Viaje = "Pérdida";
Num_Viajes++;
Total_Pasajeros += Num_Pasajeros;
}
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
Viajero.Solicitud_Viaje();
}
}
public void Reporte_Viaje()
{
JOptionPane.showMessageDialog(null, "Reporte de Viaje\nEl Tipo de Autobus fue: "+Tipo_Vehiculo+"\nEl Total de Pasajeros en el Viaje fue de: "+Num_Pasajeros+"\n"+Analisis_Viaje);
}
public void Solicitud_Viaje()
{
Empresa_Autobuses Viajero = new Empresa_Autobuses();
String Solicitud;
boolean flag = true;
do
{
Solicitud = JOptionPane.showInputDialog("¿Quiere realizar otro Viaje? (Y/N)").toUpperCase();
if(Solicitud.equals ("Y"))
{
Viajero.main();
}
else if(Solicitud.equals ("N"))
{
flag = true;
}
else
{
JOptionPane.showMessageDialog(null, "Opción Incorrecta");
flag = false;
}
}while(flag == false);
}
public void Reporte_Final()
{
Prom_Pasajeros = Total_Pasajeros / Num_Viajes;
JOptionPane.showMessageDialog(null, "El Número de Viajes realizados fue de: "+Num_Viajes+"\nEl Total de Pasajeros fue de: "+Total_Pasajeros+"\nEl Promedio de Pasajeros fue de: "+Prom_Pasajeros);
System.exit(9999);
}
}
The problem does not seem to be where you think it is. What happens when Num_Pasajeros>60? Why is the increment within a "then" block if it should always happen?
Edit
It appears very likely that the problem is that you run your main procedure from within your program. This second invocation creates a whole new object that is not related to the one you've been working with! Don't do that, and you should probably be fine. You have some issues with your Swing threading, but you probably shouldn't think about that yet.
Should debug it, take a break point # Empresa_Autobuses Viajero = new Empresa_Autobuses(); and see whats happening what case (if/else branch) is running/executing, what are your variable actual values...
Anyway if you observe it carefully: if the care type is P, then you total_pasajeros will not summed with num pasarejos.
Tipo_Vehiculo.equals ("P"))
And +1 for the Java Code Convention: http://web.archive.org/web/20140222045352/http://www.oracle.com/technetwork/java/codeconv-138413.html
(You make everybody job easier here if you keep youeself to that)
p.s: I do not know Italian language but common sense suggest these....

Categories