0

I'm new to java world, I'm writing a simple program but i'm having a problem :

here's the code :

while(choix!=7) { 

    System.out.println("Tapez un choix :") ; 
    choix=s.nextInt(); 

    switch (choix) { 
    case 1 : {  } break ;

    case 2 :{
        c.vider() ; }break ;

    case 3 :{ 
        int i,n; System.out.println("donnez le nombree de livres à ajouter"); 
        n=s.nextInt();
        for(i=0;i<n;i++) c.ajouter() ;
        }break ;

    case 4:{ 
        c.Index() ; 
        c.affichagemotsvides(); 
        c.affichageindex(); 
        } break ; 

    case 5 :{
        //s.wait();
        String aut ; 


        System.out.println("Tapez le nom de l'auteur");


        aut=s.nextLine() ; //Here's the line where i want to read the string
        if (aut !=null)
        System.out.println("==========>"+aut);

        //livre l1 =new livre();
        //l1=c.rechercheAut(aut);
        //l1.afficher(); 
    }break ; 

The first time i enter a number choix=s.nextInt(); its readed correctly when i put 5 . the aut=s.nextLine() ; don't let me write the string i want to enter. Here's the output :

1. Créer un Catalogue
2. Vider le Catalogue 
3. Ajouter des livres dans le Catalogue
4. Générer l’Index du Catalogue
5. Rechercher dans le Catalogue, par Auteur
6. Rechercher dans le Catalogue, par Mot Clé
7. Quitter
Tapez un choix :
5
Tapez le nom de l'auteur
==========>
Tapez un choix :
Amira
  • 3,184
  • 13
  • 60
  • 95

2 Answers2

1

add s.nextLine() ; before aut=s.nextLine() ;

i.e. try

    s.nextLine()
    aut=s.nextLine() ; 

Explanation :as Bohemian said in given link Scanner issue when using nextLine after nextXXX

it's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". When input.nextLine() executes, it consumes the "end of line" still in the buffer from the first input.

Instead, use input.nextLine() immediately after input.nextInt()

Community
  • 1
  • 1
Kamlesh Arya
  • 4,864
  • 3
  • 21
  • 28
1

After the nextInt() you still have the rest of the line (even if it is blank and you didn't type anything after the integer)

This means the nextLine() will read what you types after the integer.

Most likely you want to ignore everything after the integer so I suggest you do this.

choix = s.nextInt(); 
s.nextLine(); // ignore the rest of the line.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130