Variables in Methods don't save their value - java

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....

Related

My code works fine from constructor but always returns 1 using a setter

My Java teacher asked for an exponentiation exercise. He wants us to use bucle (for or while) for this, not math functions. Well, I have wrote the code but I realised that if I use the constructor, it works fine. But if I try to choose the value from a setter it always return 1.
package potencia;
public class potencia {
private int base = 0;
private int exponente = 0;
private int resultado = 1;
public int getBase() {
return base;
}
public int getExponente() {
return exponente;
}
public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa "settear" el resultado, sino que lo calcule el programa
return resultado;
}
public void setBase(int base) {
this.base = base;
}
public void setExponente(int exponente) {
this.exponente = exponente;
}
public potencia(){}
public potencia(int base, int exponente){
this.base = base;
this.exponente = exponente;
if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1
this.resultado = 1;
}
if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1
this.resultado = 1;
}
if (base > 1 && exponente > 0) {
for (int i=1; i<=exponente; i++) {
resultado *= base; // Uso de operador de asignación "*=", significa lo mismo que "resultado = resultado * base"
}
}
}
public void muestraResultado () {
System.out.println("El resultado es " + resultado);
}
}
The next example works perfectly:
package potencia;
public class calcularPotencia {
public static void main(String[] args) {
potencia MiCalculadora = new potencia(5, 4);
MiCalculadora.muestraResultado();
System.out.println(MiCalculadora.getResultado());
}
}
It returns: "El resultado es 625
625"
But when I use setters:
package potencia;
public class calcularPotencia {
public static void main(String[] args) {
potencia MiCalculadora = new potencia();
MiCalculadora.setBase(5);
MiCalculadora.setExponente(4);
MiCalculadora.muestraResultado();
System.out.println(MiCalculadora.getResultado());
}
}
Returns: "El resultado es 1
1"
I supposed that something went wrong with setters and getters, so I deleted them and inserted them again. It was resultless, the fail persists. I also have checked methods and classes, but I can not see the mistake.
Thank you all for your help, mates.
You aren't calculating the result when you use the setter.
You could remove the member variable for resultado and calculate it in the getter:
public int getResultado() { // De la variable resultado solo creamos el getter pues no nos interesa "settear" el resultado, sino que lo calcule el programa
if (exponente == 0) { // Si la variable EXPONENTE se inicializa a 0, la variable RESULTADO será 1
return 1;
}
if (base == 1) { // Si la variable BASE se inicializa a 1, la variable RESULTADO será 1
return = 1;
}
if (base > 1 && exponente > 0) {
int resultado = 1;
for (int i=1; i<=exponente; i++) {
resultado *= base; // Uso de operador de asignación "*=", significa lo mismo que "resultado = resultado * base"
}
return resultado;
} else {
throw new RuntimeException("base or exponente < 0");
}
}
You could also keep the field and cache the result after calculating it. initialize it to -1, since that is not a valid result. Then do:
public int getResultado() {
if (resultado < 0) {
calculateResultado();
}
return resultado;
}
Where the calculate method will be similar to what you are doing in the constructor (in fact you can call it from the constructor).

Java not asking for reinput after an InputMismatchException

I have a sample program which registers people for an airline.
At the Registration class, on the selectSeats method, I have a try catch block, where the catch statement should catch InputMismatchException in case the user inputs a non numeric value.
However, the reinput operation isn't happening, so instead, when an exception happens, the program just throws the error message and proceeds to the end (which leads to unexpected results)
This is the method in question
public void seleccionarAsiento() {
boolean malaSeleccion = true;
do{
try{
System.out.println("\n\n Digite el número de asiento del 0 hasta el 20");
while (malaSeleccion) {
//Selección del hashSet correspondiente a cada vuelo mediante uso de la variable polimorfica "asientos".
if(this.destino.equals("Nicaragua")) {
asientos = asientosNCA;
}
else if (this.destino.equals("Panama") || this.destino.equals("Panamá")) {
asientos = asientosPNA;
}
this.asiento = input.nextInt(); //The part causing the issue
if(this.asiento < 0 || this.asiento > 20) {
System.out.println("\nSelect a seat between 0 and 20.");
} else if (asientos.contains(this.asiento)) {
System.out.println("\nSeat taken, select another one.");
} else if (this.asiento >= 0 && this.asiento <= 20 && asientos.contains(this.asiento) == false) {
asientos.add(this.asiento);
continuarCiclo = false;
malaSeleccion = false;
}
}
} // Fin de bloque try
//Bloque catch para prevenir un input no numerico.
catch (InputMismatchException inputMismatchException) {
System.out.println("Not numeric value, try again.");
input.nextLine();
}
In case this is relevant, since I'm not sure if this could be related to a problem with Inheritance (but I doubt it because the exception is being caught)
This is the start of the class where that method is, and an extension to Exception I added.
public class RegistroCompra {
Scanner input = new Scanner(System.in);
private String destino;
private int asiento;
private boolean continuarCiclo = true;
public static HashSet<Integer> asientosNCA = new HashSet(21);
public static HashSet<Integer> asientosPNA = new HashSet(21);
HashSet<Integer> asientos = null;
class ExcepcionRegistro extends Exception {
ExcepcionRegistro(String s) {
super(s);
}
}
} while (continuarCiclo == true); // Fin de bloque Do
Edit: I solved the issue by making the method recursive in the catch block.
So if it catches the inputmismatchexception (because it was catching it), it cleans the buffer from the invalid input with input.nextLine() and then, the function calls itself again to restart the selection process.
Do it as follows:
public void selectSeat() {
boolean valid = true;
do {
System.out.println("Enter the seat number from 0 to 20");
// ...
try {
this.asient = Integer.parseInt(input.nextLine());
// ...
} catch (InputMismatchException inputMismatchException) {
System.out.println("This is not a numerical value, try again.");
valid = false;
}
} while (!valid);
}
The exception may not the instance of InputMismatchException. You could try add Exception e to take a look the real exception.
catch (InputMismatchException inputMismatchException) {
System.out.println("Este no es un valor númerico, intente de nuevo.");
input.nextLine();
}
catch (Exception e) {
exception.printStackTrace()
input.nextLine();
}

Programming OO and classes

I'm trying this ex but i cant find the problem; i can run it but it isn't as i would.
It should be a switch for light bulbs; i have my main:
import java.util.Scanner;
public class UsoLampadina {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner (System.in);
// Select the maximum number of clicks
System.out.println("Selezionare il numero massimo di click: ");
int click = scanner.nextInt();
char s;
int i= 0;
Lampadina lamp = new Lampadina ( click , i);
while (i >= 0){
// Select the operation to be performed
// V = Displays the status of the light bulb
// C = Change the state of the bulb
// Enter the selected operation:
System.out.println("Selezionare l'operazione da eseguire: ");
System.out.println("[V] Visualizza lo stato della lampadina");
System.out.println("[C] Cambia lo stato della lampadina");
System.out.println("Immettere l'operazione selezionata: ");
s = scanner.next().charAt(0);
switch (s) {
case 'V': lamp.Stato(); break;
case 'C': i = lamp.Click(); break;
// Select a correct character
default: System.out.println(" Selezionare un carattere corretto");
}
}
// The light bulb broke!!!
System.out.println("La lampadina si è rotta!!!");
return;
}
}
That open a menu where u can choose to see if the bulb is on or off (lamp.Stato()) or to change it state (turn off if it is on and viceversa, lamp.Click()).
And my second class:
public class Lampadina {
public int maxClick;
public int c = 0;
public int i;
public Lampadina ( int a, int b) {
a = maxClick;
b = i;
}
public int Click() {
while (click >= c ) {
if ( i == 1 ) {
c++;
i = 0;
return i;
}
else if (i == 0) {
c++;
i = 1;
return i;
}
}
i = -1;
return i;
}
public void Stato () {
if (i == 0) {
// The light bulb is off
System.out.println("La lampadina è spenta");
}
else if (i == 1) {
// The light bulb is on
System.out.println("La lampadina è accesa");
}
else if (i == -1) {
// The light bulb is broken
System.out.println("La lampadina è rotta");
}
}
}
Here i have the bulb's constructor method; and auxiliares (Click, Stato).
"Stato" works but i have problems with "Click"; it doesn't do what it should:
the idea is that if the bulb is turned off (i == 0) it tunrs it on (return i = 1) and viceversa; c is a counter that, when it reachs the maxClicks (that u give as input in the main as a parametrer of the object "bulb") number; the bulb breaks.
when i run the programm it doesnt do the right number of cicle before the lamp breaks down
you are setting parameter a and b to values instead set values to parameters
public Lampadina(int a, int b) {
maxClick=a;
i=b;
}

Java Prime Numbers Client/Server

I am making an application that tells you if the number you enter is prime or not.The problem I have is that it only asks once and terminates the program.
How could I do to keep asking numbers and the program ends when enter the number 0?
Updated Code.
public class numerosPrimos {
public static String CheckPrimo(int numero){
int contador = 0;
int residuo = 0;
int divisores = 0;
for (contador=1;contador<=numero;contador++)
{
residuo=numero%contador;
if(residuo==0)
{
divisores++;
}
}
if(divisores>=3)
{
return "El numero "+numero+" no es primo";
}
else
{
return "El numero "+numero+" es primo";
}
}
}
Thank you in advance guys!
Simple said:
Put everything in the main method of the client into a while loop and add an if-branch to jump out of the programm if the given number is 0.
Have you tried putting a loop into your client program (instead of calling System#exit after just one number)?
And on the server-side, don't close the server socket. If you do, no one can connect anymore.
The problem was on my class, I got all declared as static, I corrected it starting the variables inside "CheckPrimo" like this:
public class numerosPrimos {
public static String CheckPrimo(int numero){
int contador = 0;
int residuo = 0;
int divisores = 0;
for (contador=1;contador<=numero;contador++)
{
residuo=numero%contador;
if(residuo==0)
{
divisores++;
}
}
if(divisores>=3)
{
return "El numero "+numero+" no es primo";
}
else
{
return "El numero "+numero+" es primo";
}
}
}
Thank you for your help :)

toggle a variable to true/false with a JButton

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.

Categories