How to instantiate a public void object in JAVA?

1

I have a public class where I write the methods and the main from which I instancio to solve the exercises / problems. I wish to instantiate the following method:

public class metodos {
   public void espositivo(int a) {
    if (a>0) {
        System.out.println("El numero es POSITIVO");
    }
    else{
         System.out.println("El numero es NEGATIVO");
    }  
  }
}

This is my main:

import java.util.Scanner;
public class principal {
public static void main (String [] args) {
     metodos op=new metodos();
    Scanner leer= new Scanner(System.in);
    int a=0;

  System.out.println("Ejercicio 2.1");
  System.out.println("");
  System.out.println("Ingrese un numero para saber si es positivo o no");
  a=leer.nextInt();
  //posOneg=op.espositivo(a);
}
}

The error appears in the commented line.

    
asked by Die Duro 20.06.2017 в 21:32
source

3 answers

1

Being a void method, it does not return something. Inside it prints something through the System.out.println () . So just enough:

op.espositivo(a);

So that the method validates your if and with it you will know what to print by console. I hope my explanation has been useful, greetings.

    
answered by 20.06.2017 / 21:36
source
3

The error does not show it, but for its commented line the "possible error" is that it tries to assign to a variable the value that returns its method espositivo , but this method does not return any value void .

Then to execute your method it would be enough to call the method and not assign to any variable, I also added a method to validate the input if is not, re-request the entry.

System.out.println("Ingrese Número");
/* Verificamos si existe un token de tipo int ,
   si no existe volvemos a solicitar la entrada  */
while (!leer.hasNextInt()) {
    System.out.println("Vuelva a Ingresar el Número");
    leer.next(); /* Nueva Entrada*/
}
/* Asignamos el valor a la variable a*/
int a = leer.nextInt();
System.out.println(a);
op.espositivo(a);
  

Remember that you always have to validate entries if you can not launch a   exception NumberFormatException

    
answered by 20.06.2017 в 21:48
0

If you only want to print in console if the value of a is positive / negative, just call the method:

op.espositivo(a);

The espositivo() method does not return any value since it has a return value of type void , if you want a boolean value to return it simply defines the type of return value as boolean and ensures return this type of value within the method:

public class metodos {
   public boolean espositivo(int a) {
    if (a>0) {
        System.out.println("El numero es POSITIVO");
        return true;
    }
    else{
         System.out.println("El numero es NEGATIVO");
         return false;
    }  
  }
}

This way you can use the method and it would give you a value true or false depending on the value of a :

  boolean posOneg = op.espositivo(a);
    
answered by 20.06.2017 в 23:45