1

Good morning, I'm learning Java, I had a problem and I don't know what the solution is... I want to add a certain amount of data (name, address, money) to an arraylist, I do a for loop for this and when executing the Variable reading is not done correctly. When I use nextLine to read variable 0, the program jumps to 1, so I don't enter the amount of information I want Now, when I use next() this doesn't happen, but when I want to enter a space-separated name as data, the same jump is done as if I were using nextLine... does anyone have any recommendations? arrays

my code is not finished since I can't go from here

public static void main(String\[\] args) {
    Scanner sc = new Scanner(System.in);
    List <Cliente> lista = new ArrayList<Cliente>(); //declaracion y asignacion del ArrayList
    Cliente clie = new Cliente();

    System.out.println("De la cantidad de cientes a ingresar: ");
    int n = sc.nextInt();
    
    for (int i = 0; i < n; i ++) {
        //lista.add(new Cliente("nico","ramos ",1,25000));
        System.out.println("Al cliente se le asigno un numero de cliente");
        clie.setCodigoCliente(i);
        System.out.println("Ingrese el nombre del cliente " +i);
        String nom;
        clie.setNombre(nom = sc.nextLine());
        System.out.println("Ingrese la direccion del cliente "+i);
        String direccion;
        clie.setDireccion(direccion = sc.nextLine());
    }
}
public class Cliente {

    int codCliente;
    String nombre;
    String direccion;
    double credito;

    public Cliente() { }

    public Cliente(String nombre, String direccion, double credito) {
        // this.codCliente = codCliente;
        this.nombre = nombre;
        this.direccion = direccion;
        this.credito = credito;
    }

    // Getters and setters omitted for brevity

}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • 1
    Is ‘ i \< n’ intentional or a typo: ‘ i < n’? – John Williams Mar 27 '23 at 18:41
  • 1
    Could you provide a bit more clarification around the input file you are using? It seems like the first thing you do is to read an integer value with sc.nextInt() before entering the for loop. Could you please format your post so all your code is actually ina code block? I would make it more easy to ready. – 9DA Mar 27 '23 at 19:11
  • ok, now formulate it in a better way – Nicolas Ramos Mar 27 '23 at 20:00
  • In a business that is dedicated to the sale of electrical supplies, it has the information of its clients in the following structure. int cliCode; //customer code char NameName[40]; //last name and name char dire[60]; //home address float monCred; //Maximum amount of credit you can make on each purchase. is requested: • Enter the data N customers. • As customers are entered, using a function to display the registered data. • At the end of the loading of the N customers, show how many customers have a credit amount greater than $30,000. – Nicolas Ramos Mar 27 '23 at 20:02
  • this is what i should do – Nicolas Ramos Mar 27 '23 at 20:03
  • Firstly, I want to store the data in an arraylist, for this I made a class called clients and declaring all the variable decesarias and their corresponding setters and gettes. then in the main I create an arraylist, an object of type client. The next step is to ask the user to enter n which is the number of customers to register and is the number of times the for loop will iterate. then I would have to ask the user to enter the name, address and money of the clients and here comes the problem, assuming that my n=3 the for loop would iterate from 0 to 2, but the name of the client 0 (n = 0) – Nicolas Ramos Mar 27 '23 at 20:20
  • he skips and directly asks me for his address ex: for ( i = 0 ; i < 3 ; i++) enter customer name name = scan.nextLine(); enter customer address direction = scan.nextLine(); enter customer money money = scan.netInt(); when executing this step the first read of the variable name is skipped and asks me to directly enter the address of the client, this only happens with the first variable once, then the execution continues normally – Nicolas Ramos Mar 27 '23 at 20:21
  • That said, I was trying instead of using the nextLine to use the next(), with the latter it does not jump to the second variable but I can only put words without spaces since if I put for example "matias gonzales" the same thing happens as with the nextLine skip a variable read – Nicolas Ramos Mar 27 '23 at 20:21

2 Answers2

0

Try this code:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ClientTest {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    List<Cliente> lista = new ArrayList<Cliente>(); //declaracion y asignacion del ArrayList Cliente clie = new Cliente();
    System.out.println("Enter how many clients will be added:");
    int n = sc.nextInt(); // if you will type here '2 abc' then
//n will be '2' and nextLine will be ' abc' that's why 'sc = new Scanner(System.in)' is used to reset the scanner

    sc = new Scanner(System.in);
    for (int i = 0; i < n; i++) {

        Cliente cliente = new Cliente();
        cliente.setCodigoCliente(i);
        System.out.println("Enter number of client# " + i);
        cliente.setNombre(sc.nextLine());
        System.out.println("Enter direccion of client: " + i);
        cliente.setDireccion(sc.nextLine());
        lista.add(cliente);
    }
    System.out.println(lista);
}

}

class Cliente {

int codCliente;
String nombre;
String direccion;
double credito;

public Cliente() {

}

public Cliente(String nombre, String direccion, double credito) {
    // this.codCliente = codCliente;
    this.nombre = nombre;
    this.direccion = direccion;
    this.credito = credito;
}

@Override
public String toString() {
    return "Cliente{" +
            "codCliente=" + codCliente +
            ", nombre='" + nombre + '\'' +
            ", direccion='" + direccion + '\'' +
            ", credito=" + credito +
            '}';
}

public void setCodigoCliente(int codCliente) {
    this.codCliente = codCliente;
}

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

public void setDireccion(String direccion) {
    this.direccion = direccion;
}

public void setCredito(double credito) {
    this.credito = credito;
}

public int getCodCliente() {
    return codCliente;
}

public String getNombre() {
    return nombre;
}

public String getDireccion() {
    return direccion;
}

public double getCredito() {
    return credito;
}
}
0

Change String nombre to int nombre since you want that to be an incrementing number rather than text.

If the main purpose of your class Cliente is to communicate data transparently and immutably, define your class as a record.

public record Cliente( int nombre , String direccion , double credito ) { }

Tip: A record can be defined locally within a method, or nested within another class, or in its own standalone .java file.

With your scanner collect all the needed data before instantiating the client. Generally best to separate user-interface from other code.

When using scanner commands such as nextInt and nextDouble, be sure to consume the leftover end-of-line with a call to nextLine. See Answers on this Question.

record Cliente( int nombre , String direccion , double credito ) { }
Scanner scanner = new Scanner( System.in );

System.out.println( "How many?" );
int count = scanner.nextInt();
scanner.nextLine(); // Consume the end-of-line left over from the `nextInt` call.
List < Cliente > clientes = new ArrayList <>( count );  // When convenient and sensible, specify the initial capacity of a new `ArrayList`.

for ( int nth = 1 ; nth <= count ; nth++ )
{
    // Gather inputs from user-interface.
    System.out.println( "direccion: " );
    String d = scanner.nextLine();

    System.out.println( "credito: " );
    double c = scanner.nextDouble();
    scanner.nextLine(); // Consume the end-of-line left over from the `nextDouble` call.

    // Instantiate business object.
    Cliente cliente = new Cliente( nth , d , c );
    clientes.add( cliente );
}
System.out.println( clientes );
How many?
3
direccion: 
one
credito: 
1.1
direccion: 
two
credito: 
2.2
direccion: 
three
credito: 
3.3
[Cliente[nombre=1, direccion=one, credito=1.1], Cliente[nombre=2, direccion=two, credito=2.2], Cliente[nombre=3, direccion=three, credito=3.3]]
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thanks for your help, I saw your code and compared it with mine, I don't have much knowledge about how the scanner works and your comment about it gave me an idea of what was the mistake I was making... Greetings from Argentina <3 – Nicolas Ramos Mar 28 '23 at 11:57