代码之家  ›  专栏  ›  技术社区  ›  bobbyrne01

在java中从键盘获取多行和单个字符[duplicate]

  •  0
  • bobbyrne01  · 技术社区  · 7 年前

    我输入:

    • IT工程师(按回车键)

    然后发生的是,循环再次发生,但您不能进入 your first and last name

    String name = s.nextLine();

    为什么?

    代码:

    Scanner s = new Scanner(System.in);
    
    do {
        System.out.printl('Enter your first and last name:');
        String name = s.nextLine();
    
        System.out.printl('Enter your job description:');
        String job = s.nextLine();
    
        System.out.println("Press Y for loop ..");
        char answer = s.next().charAt(0);
    } while(answer == 'Y');
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   suvojit_007    7 年前

    System.out.printl() System.out.println()

    字符串应该使用双引号。

     System.out.printl('Enter your first and last name:');//<----single quote
    

    变量 answer {} . 声明 回答 在 do-while

    而不是使用 char answer = s.next().charAt(0); answer = s.nextLine().charAt(0);

    更多信息请查看 Scanner is skipping nextLine() after using next() or nextFoo()?

    这是您修改后的代码:

        public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char answer; //<----declare the variable here 
    
    do {
        System.out.println("Enter your first and last name:"); //<---use double quotes
        String name = s.nextLine();
    
        System.out.println("Enter your job description:");//<---use double quotes
        String job = s.nextLine();
    
        System.out.println("Press Y for loop ..");
        answer = s.nextLine().charAt(0); //<---use nextLine() here 
    }while(answer == 'Y');
    }