Java阅读线与扫描仪

时间:2013-12-08 15:32:41

标签: 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 :

2 个答案:

答案 0 :(得分:1)

s.nextLine() ;

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

即。 尝试

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

解释:波希米亚人在给定的链接Scanner issue when using nextLine after nextXXX

中说

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

而是在input.nextInt()

之后立即使用input.nextLine()

答案 1 :(得分:1)

nextInt()之后你仍然拥有剩余的一行(即使它是空白的,你没有在整数后输入任何内容)

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

很可能你想忽略整数之后的所有内容,所以我建议你这样做。

choix = s.nextInt(); 
s.nextLine(); // ignore the rest of the line.
相关问题