Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

closed why shoud i add this line ? JAVA

+9 votes
asked Nov 19, 2021 by Wryyy!! (640 points)
closed Nov 20, 2021 by Admin

Hello word !

i was doing some java exercices, and there is one who ask to write a program that asks the user to enter the size and values (of type string) of an array and display them on the screen.

this is the code : 

public static void main(String[] args) {

       

        Scanner clv =new Scanner(System.in);

        System.out.println("entrez la taille de T ");

        int n=clv.nextInt(); 

        String T[] = new String[n];

        clv.nextLine();  //why ??

        for(int i=0;i<n;i++){

            System.out.println("entrez le contenue de T["+i+"]");

            T[i] =clv.nextLine();

        }

        for(int j=0;j<n;j++){

            System.out.println("T["+j+"] = "+T[j]);

        }

    }

when  i delete the line on red color the first element T[0] is saved on T[1], T[1] on T[2] and so on... i don't understand why?

Thank you for read and sorry for my bad English :)

closed with the note: answered

2 Answers

+4 votes
answered Nov 19, 2021 by Peter Minarik (84,720 points)
selected Nov 19, 2021 by Wryyy!!
 
Best answer

nextLine() reads everything from the input and leaves the input buffer empty.

nextInt() only reads the next integer and leaves everything else following the read number on the input buffer, such as the newline character (ENTER, if you prefer).

Calling nextLine() in the highlighted line makes sure your input buffer is empty. If you don't do that, when you call nextLine() 3 lines below there is no need for user input as Java finds the input buffer non-empty. That's why your T[0] will be populated with an empty string without any user input.

I hope this cleared things up.

Good luck! :)

commented Nov 19, 2021 by Wryyy!! (640 points)
awesome thank you for your time ! :D
+1 vote
answered Nov 19, 2021 by Wryyy!! (640 points)

For people who still don't understand  Peter Minarik 's answer there is a detailed video that explains how nextLine and nextInt work 

https://www.youtube.com/watch?v=bbCr7CE97lU

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...