How to save value asked with a scanner

0

Good morning I'm working with java for a class project and I have a question.
I have a class named Modul and another one of class Alumne.
In the Alumne class I have declared an Array attribute of type Modul:

ArrayList <Modul> modul = new ArrayList <Modul>();

because a student can have several modules.

the fact is that in the mainClass when I want I want to save the modules asked with the scanner nose how to specify that it is modul type what to save.
For example when we ask a question and the attribute to save is of type String we keep it like this:% variable = EjemploScanner.next();

That's what I do not know how to do so instead of telling you that the data to be saved will be modul type in String or int accounts etc.

    
asked by Javi Palacios 10.11.2016 в 12:35
source

2 answers

0

If you are going to generate an object depending on what the user enters by keyboard, I recommend that you order it by entering it

You create your class

public class Modul{
    public int numero;
    public String nombre;

    public Modul(int numero, String nombre){
        this.numero = numero;
        this.nombre = nombre;
    }

    public int getNumero(){
        return numero;
    }

    public String getNombre(){
        return nombre;
    }

    public void setNumero(int numero){
        this.numero = numero;
    }

    public void setNombre(String nombre){
        this.nombre = nombre;
    }
}

And when you read what was entered by keyboard:

Scanner input =new Scanner (System.in);
System.out.println("Ingrese numero"); 
int numero = input.nextInt();
System.out.println("Ingrese nombre"); 
String nombre = input.next();
Modul modul = new Modul(numero, nombre);
ArrayList<Modul> listaModul = new ArrayList<Modul>();
listaModul.add(modul);

Java has too many methods that validate the type of input it is receiving and if there is even more data.

Scanner documentation It's in English but with the google translator it's perfectly understood!

    
answered by 10.11.2016 / 13:28
source
0

You can collect the primitive values (I think it is not possible to enter an object directly by Scanner) and then create an instance of that class with the reserved word new .

String unStringCualquiera = EjemploScanner.next();
int unIntCualquiera = EjemploScanner.nextInt();
Modul variable = new Modul(unStringCualquiera, unIntCualquiera);

In this example I'm assuming that EjemploScanner is your variable Scanner and that in the constructor of your class Modul you have as parameters a String and a int to build the instantancia of your class Modul .

    
answered by 10.11.2016 в 13:19