#Scanner type problem

9 messages · Page 1 of 1 (latest)

stoic light
#

I am new to java and I am trying to do a code where I use scanner to have all my variables been put by the user. The problem is that when i need to put different types as input, the string i print to ask for different types print together and they take the same input in nextInt() or nextString(); it gives me a error because they are a different types. How can i make them to "wait" for their turn?

package ese_9;
import java.util.Scanner;
import java.util.ArrayList;

public class main {

    public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.println("Quanti clienti si vuole aggiungere?");
            int j=input.nextInt();

            new ArrayList<Cliente>();
            ArrayList<Cliente> gente= new ArrayList<Cliente>();
            for (int i=0; i <j;i++ ) {
            System.out.println("Inserire nome cliente: ");
            String nome= input.nextLine();
            System.out.println("Inserire identificativo del cliente: ");
            int id=input.nextInt();
            System.out.println("Inserire il numero di conto bancario del cliente: ");
            int idconto=input.nextInt();
            System.out.println("Inserire il saldo iniziale del cliente: ");
            double saldo=input.nextDouble();
            

            gente.add(new Cliente(nome, id));
            }
            System.out.println(gente);
    }

}

i will put the class Cliente just to understand better

package ese_9;

public class Cliente {
    private String nome;
    private int id;
    public Cliente(String nome,int i) {
        this.nome=nome;
        this.id=i;
    }
    
    public String getNome() {
        return nome;
    }
    
    public int getid() {
        return id;
    }
}

whole cragBOT
#

This post has been reserved for your question.

Hey @stoic light! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

mellow crag
#

You could use next() rather than nextLine(). The data model involved makes it so mixing nextLine() with any other next()-like method produces confusion

#

Using next() rather than nextLine() is the easy fix. However, realistically, users can't type in anything but lines in the console. So the only way to truly react to what the other does, is to use nothing but nextLine(). The other methods corrupt the reality of the exchange

stoic light
whole cragBOT
mellow crag
stoic light
#

okay, thank you so much