简体   繁体   English

用于不同类型输入的不同 Java Scanner

[英]Different Java Scanner for input of different types

Imagine the following scanario: I have a program which ask for an integer input, followed by a String input.想象一下下面的扫描:我有一个程序要求一个整数输入,然后是一个字符串输入。

int age=0;
String name;
Scanner sc = new Scanner(System.in);

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc.nextLine();

With the aobe codes, I was not given a chance to enter the name.使用 aobe 代码,我没有机会输入名字。 So normally I will declare 2 scanner objects as follows:所以通常我会声明2个扫描器对象如下:

int age=0;
String name;
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);    //2nd Scanner object

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc2.nextLine();                    //Using 2nd Scanner Object

My question is: Is it necessary to declare multiple scanner objects to accept inputs of different types??我的问题是:是否有必要声明多个扫描仪对象来接受不同类型的输入? Am I doing the proper way as aobve?我在做正确的方式吗?

I have this question in mind for years already.这个问题我已经想了好几年了。 (Several questions in SO mention multiple scanner, but their questions only used one scanner object, so I am asking this today.) (SO中的几个问题提到了多个扫描仪,但他们的问题只使用了一个扫描仪对象,所以我今天问这个。)

@skiwi is right about only using one Scanner , so you're doing that right. @skiwi 关于只使用一个Scanner是正确的,所以你做对了。 The reason it doesn't work is that nextInt() consumes all characters that make up the integer, but it does not touch the end-of-line character.它不起作用的原因是nextInt()消耗了构成整数的所有字符,但它没有触及行尾字符。 So when nextLine() is called, it sees that there are no characters before the end-of-line character, so it thinks that an empty line was entered, and you get an empty String back.所以当nextLine()时,它看到行尾字符之前没有字符,所以它认为输入了一个空行,你得到一个空字符串。 However, nextLine() does consume the end-of-line character, so if you call sc.nextLine();但是, nextLine()确实会消耗行尾字符,因此如果您调用sc.nextLine(); once before you do name = sc.nextLine();在你做之前一次name = sc.nextLine(); , it should work. ,它应该工作。

You were not given a chance to enter the name because nextInt() doesn't read the new-line character '\\n' (inputted by user after pressing Enter ), whereas nextLine() does.您没有机会输入名称,因为nextInt()不会读取换行符'\\n' (用户在按下Enter后输入),而nextLine()会。 So as soon as you call name = sc.nextLine();因此,只要您调用name = sc.nextLine(); , it will just read the '\\n' character that the nextInt() didn't read already. ,它只会读取nextInt()尚未读取的'\\n'字符。

Definitely do not create a new Scanner if the Scanner if you're scanning the same thing (like System.in ) - only change Scanners if you are scanning something else, like different files or something.如果您正在扫描相同的东西(例如System.in ),绝对不要创建新的 Scanner - 如果您正在扫描其他东西,例如不同的文件或其他东西,请仅更改 Scanners。

To get your code working (with only one Scanner instance), use this:要让您的代码正常工作(只有一个 Scanner 实例),请使用以下命令:

int age = 0;
String name;
Scanner sc = new Scanner(System.in);

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");

sc.nextLine(); // "dispose" of the '\n' character
               // so that it is not recorded by the next line

name = sc.nextLine();

// print your findings
System.out.println("------\nAge: " + age + "\nName: " + name);

Example input/output:示例输入/输出:

Enter Age: 17
Enter Name: Michael
------
Age: 17
Name: Michael

You should use only one Scanner instance per object that you are scanning.对于要扫描的每个对象,您应该只使用一个Scanner实例。 In this case you are reading from the System.in , so opening two scanners on the same them concurrently does not even make sense.在这种情况下,您正在从System.in读取数据,因此同时在同一台上打开两个扫描仪甚至没有意义。

So you definately want to go with your first option, then the question comes, what is wrong with it:所以你肯定想选择你的第一个选项,那么问题来了,它有什么问题:

Well, you ask for sc.nextInt() , an integer, and a name rarely is an integer.好吧,您要求sc.nextInt()一个整数,而名称很少是整数。 You are most likely looking for either name = sc.next() for one word or for name = sc.nextLine() for a whole sentence (until the enter key has been pressed).您很可能会为一个单词寻找name = sc.nextLine() name = sc.next()为整个句子寻找 name = sc.nextLine() (直到按下回车键)。

Also be aware that after sc.nextInt() , actually after any sc.next***() , you need to press Enter .另请注意,在sc.nextInt()之后,实际上在任何sc.next***()之后,您需要Enter

您还可以使用:

name = sc.next();

This must work perfectly.这必须完美地工作。 I tested it out.我测试了它。

int age=0;
String name;
Scanner sc = new Scanner(System.in);

System.out.print("Enter Age: ");
age = sc.nextInt();
System.out.print("Enter Name: ");
name= sc.nextLine();

why this code has not work?为什么这段代码不起作用?

package Programs;
import java.util.Scanner;
public class LibraryManagement {
    Scanner s = new Scanner(System.in);
    String Sname, Bname, Bauthor;
    int Sid,Sclass,Bid;
    void StudInfo()
    {
    
    System.out.print("Enter the Student Id: ");
    Sid=s.nextInt();
    
    System.out.print("Enter the Student name: ");
    Sname=s.nextLine();
    
    System.out.print("Enter the Student Class: ");
    Sclass=s.nextInt();
    
    System.out.println("Student detail is saved:  \n Id : "+ Sid + " Name : "+ Sname+ " Class : ");
    
    }
    public static void main(String[] args) {
          LibraryManagement obj= new LibraryManagement();
          obj.StudInfo();
        }
    
    }

output is :输出是:
Enter the Student Id: 10输入学生号:10
Enter the Student name: Enter the Student Class:输入学生姓名: 输入学生班级:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM