How to read strings from a Scanner in a Java console application?

后端 未结 4 593
萌比男神i
萌比男神i 2020-12-01 18:46
import java.util.Scanner;
class MyClass
{
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        int employeeId,          


        
相关标签:
4条回答
  • 2020-12-01 19:05

    Replace:

    System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
    

    with:

    System.out.println("Enter EmployeeName:");
                     ename=(scanner.nextLine());
    

    This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

    0 讨论(0)
  • 2020-12-01 19:08

    You are entering a null value to nextInt, it will fail if you give a null value...

    i have added a null check to the piece of code

    Try this code:

    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());
                    System.out.println("Enter EmployeeName:");
                         ename=(scanner.next());
                    System.out.println("Enter SupervisiorId:");
                        if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                         sid=scanner.nextInt();
                         }//null check
            }
    }
    
    0 讨论(0)
  • 2020-12-01 19:17

    What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.

    Scanner sc = new Scanner(System.in);
    sc.useDelimiter(System.getProperty("line.separator"));
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 19:20
    Scanner scanner = new Scanner(System.in);
    int employeeId, supervisorId;
    String name;
    System.out.println("Enter employee ID:");
    employeeId = scanner.nextInt();
    scanner.nextLine(); //This is needed to pick up the new line
    System.out.println("Enter employee name:");
    name = scanner.nextLine();
    System.out.println("Enter supervisor ID:");
    supervisorId = scanner.nextInt();
    

    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.

    0 讨论(0)
提交回复
热议问题