Scanner is not taking input of another string and skipping it

微笑、不失礼 提交于 2019-12-11 08:54:27

问题


Why scanner is not taking input of another string and skepping it? I cant understand, here is my code:

import java.util.Scanner;

public class demo {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        String name;
        String address;
        int age;

        System.out.println("Enter your name");
        name = s.nextLine();
        System.out.println("My name is :" + name);

        System.out.println("Enter your age");
        age = s.nextInt();
        System.out.println("My age is :" + age);

        System.out.println("Enter your address");
        address = s.nextLine();
        System.out.println("My address is :" + address);
    }
}

Output :

Enter your name
dk
My name is :dk
Enter your age
22
My age is :22
Enter your address
My address is :


回答1:


It is simple. You can use s.nextLine(); after the age = s.nextInt();

Scanner provides a method nextInt() to request user input and does not consume the last newline character (\n).

System.out.println("Enter your age");
age = s.nextInt();
s.nextLine(); // consumes the \n character
System.out.println("My age is :" + age);



回答2:


You should close the scanner after the last system out




回答3:


Place below statement after Statement.out.println("My age is",age);

s.nextLine();

Above statement will do flush, which will clear the cache location in order to accept new input.



来源:https://stackoverflow.com/questions/50675707/scanner-is-not-taking-input-of-another-string-and-skipping-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!