Use of nextLine() in java

Asked

Viewed 39 times

0

Hello I started studying java a little while ago and I came across a problem :

import java.util.Scanner; 
public class MainD {    
public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);      
            int i = scan.nextInt();
            
            if(i == 1) {
                System.out.println("string a");
                String a = scan.nextLine();
                System.out.println("string b");
                String b = scan.nextLine();
            }
    }
}

Seal on executing.

1
Digite a string a
Digite a string b

When executing this code he ends up executing the four lines stopping only in the last nextLine(), next() would solve this but only add a word, someone could explain to me why, since I thank you. ps I am studying programming just 3 weeks.

1 answer

0

The problem is that the nextInt() does not consume the line break character \n, then the subsequent call from nextLine() consumes it, causing the program to skip to the reading of the string b.

You need to consume the line break \n before reading the string a.

import java.util.Scanner;

public class MainD {    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);      
        int i = scan.nextInt();
        
        if(i == 1) {
            scan.nextLine(); // Essa linha faz com que o `\n` que restou do input numérico seja consumido.
            System.out.println("string a");
            String a = scan.nextLine();
            System.out.println("string b");
            String b = scan.nextLine();
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.