且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从控制台应用程序JAVA中的扫描仪读取字符串?

更新时间:2023-01-11 19:11:19

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());  
        }
}

调用nextInt()是一个问题,因为它没有'拿起新线(当你按下回车键)。因此,在此之后调用scanner.nextLine()可以正常工作。

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.