What's the difference between next() and nextLine() methods from Scanner class?

后端 未结 14 2028
你的背包
你的背包 2020-11-21 05:32

What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be \"con

14条回答
  •  伪装坚强ぢ
    2020-11-21 06:18

    I also got a problem concerning a delimiter. the question was all about inputs of

    1. enter your name.
    2. enter your age.
    3. enter your email.
    4. enter your address.

    The problem

    1. I finished successfully with name, age, and email.
    2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

    The solution

    I used the delimiter for my scanner and went out successful.

    Example

     public static void main (String args[]){
         //Initialize the Scanner this way so that it delimits input using a new line character.
        Scanner s = new Scanner(System.in).useDelimiter("\n");
        System.out.println("Enter Your Name: ");
        String name = s.next();
        System.out.println("Enter Your Age: ");
        int age = s.nextInt();
        System.out.println("Enter Your E-mail: ");
        String email = s.next();
        System.out.println("Enter Your Address: ");
        String address = s.next();
    
        System.out.println("Name: "+name);
        System.out.println("Age: "+age);
        System.out.println("E-mail: "+email);
        System.out.println("Address: "+address);
    }
    

提交回复
热议问题