Skip to main content

APIzation: Replication Package

[Q#17691162][A#17691245] How to Read Strings from Scanner in console Application JAVA?

https://stackoverflow.com/q/17691162

I got Output While Trying to insert this but its working on this What I want is that i must read the full string whether it is given as name or as firstname lastname..Eg:-(john –> is accepted by scanner.next(); but john carter is not accepted by scanner.next(); )

Answer

https://stackoverflow.com/a/17691245

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

APIzation

import java.util.Scanner;

class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                eid=scanner.nextInt();
                scanner.nextLine(); //This is needed to pick up the new line
                System.out.println("Enter EmployeeName:");
                ename=scanner.nextLine();
                System.out.println("Enter SupervisiorId:");
                sid=(scanner.nextInt());  
        }
}
package com.stackoverflow.api;

import java.util.Scanner;

public class Human17691245 {

  public static Object[] readStringsfromScanner() {
    Scanner scanner = new Scanner(System.in);
    int eid, sid;
    String ename;
    System.out.println("Enter employee ID:");
    eid = scanner.nextInt();
    scanner.nextLine(); // This is needed to pick up the new line
    System.out.println("Enter employee name:");
    ename = scanner.nextLine();
    System.out.println("Enter supervisor ID:");
    sid = scanner.nextInt();
    scanner.close();
    return new Object[] { employeeId, name, supervisorId };
  }
}

package com.stackoverflow.api;

import java.util.Scanner;

/**
 * How to Read Strings from Scanner in console Application JAVA?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/17691245">https://stackoverflow.com/a/17691245</a>
 */
public class APIzator17691245 {

  public static void readStrings() {
    Scanner scanner = new Scanner(System.in);
    int eid, sid;
    String ename;
    System.out.println("Enter Employeeid:");
    eid = scanner.nextInt();
    // This is needed to pick up the new line
    scanner.nextLine();
    System.out.println("Enter EmployeeName:");
    ename = scanner.nextLine();
    System.out.println("Enter SupervisiorId:");
    sid = (scanner.nextInt());
  }
}