2013-12-08 176 views
0

Java的读线我是新来的Java世界, 我正在写一个简单的程序,但我有一个问题:与扫描仪

下面的代码:

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 ; 

第一次我输入一个数字choix=s.nextInt(); 当我放5时,它正确地加速了。 aut=s.nextLine() ;不要让我写我想输入的字符串。 下面是输出:

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 : 

回答

1

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

即 尝试

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

说明:波希米亚中给出的链接表示Scanner issue when using nextLine after nextXXX

这是因为当你进入麻木然后按Enter键,input.nextInt()只消耗数字,而不是“行尾”。当input.nextLine()执行时,它会从第一个输入中消耗仍在缓冲区中的“行尾”。

改用input.nextLine()后立即input.nextInt()

1

nextInt()你仍然有行(其余哪怕是空白的,你整后没有输入任何内容)

这意味着nextLine()将读取您在整数后键入的内容。

最有可能你想忽略整数后的所有东西,所以我建议你这样做。

choix = s.nextInt(); 
s.nextLine(); // ignore the rest of the line.