简体   繁体   English

如何使用 Java 中的扫描仪 class 从控制台读取输入?

[英]How can I read input from the console using the Scanner class in Java?

How could I read input from the console using the Scanner class?如何使用Scanner class 从控制台读取输入? Something like this:像这样的东西:

System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.基本上,我想要的只是让扫描仪读取用户名的输入,并将输入分配给String变量。

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in .一个说明java.util.Scanner如何工作的简单示例是从System.in读取单个整数。 It's really quite simple.这真的很简单。

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

To retrieve a username I would probably use sc.nextLine() .要检索用户名,我可能会使用sc.nextLine()

System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);

You could also use next(String pattern) if you want more control over the input, or just validate the username variable.如果您想对输入进行更多控制,也可以使用next(String pattern) ,或者仅验证username变量。

You'll find more information on their implementation in theAPI Documentation for java.util.Scanner您可以在java.util.ScannerAPI 文档java.util.Scanner找到有关其实现的更多信息

Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();

Reading Data From The Console从控制台读取数据

  • BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. BufferedReader是同步的,因此可以从多个线程安全地完成对 BufferedReader 的读取操作。 The buffer size may be specified, or the default size( 8192 ) may be used.可以指定缓冲区大小,或者可以使用默认大小( 8192 )。 The default is large enough for most purposes.对于大多数用途,默认值足够大。

    readLine() « just reads data line by line from the stream or source. readLine() «只是从流或源中逐行读取数据。 A line is considered to be terminated by any one these: \\n, \\r (or) \\r\\n一行被认为由以下任何一个终止:\\n、\\r(或)\\r\\n

  • Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\\s) and it is recognised by Character.isWhitespace . Scanner使用分隔符模式将其输入分解为标记,默认情况下匹配空格(\\s)并且它被Character.isWhitespace识别。

    « Until the user enters data, the scanning operation may block, waiting for input. «直到用户输入数据,扫描操作可能会阻塞,等待输入。 « Use Scanner( BUFFER_SIZE = 1024 ) if you want to parse a specific type of token from a stream. «如果您想从流中解析特定类型的令牌,请使用 Scanner( BUFFER_SIZE = 1024 )。 « A scanner however is not thread safe. «然而,扫描器不是线程安全的。 It has to be externally synchronized.它必须是外部同步的。

    next() « Finds and returns the next complete token from this scanner. next() « 从这个扫描器中查找并返回下一个完整的标记。 nextInt() « Scans the next token of the input as an int. nextInt() « 将输入的下一个标记扫描为 int。

Code代码

String name = null;
int number;

java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);

java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next();  // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);

// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
    // Read a line from the user input. The cursor blinks after the specified input.
    name = cnsl.readLine("Name: ");
    System.out.println("Name entered: " + name);
}

Inputs and outputs of Stream Stream 的输入和输出

Reader Input:     Output:
Yash 777          Line1 = Yash 777
     7            Line1 = 7

Scanner Input:    Output:
Yash 777          token1 = Yash
                  token2 = 777

There is problem with the input.nextInt() method - it only reads the int value. input.nextInt() 方法存在问题 - 它只读取 int 值。

So when reading the next line using input.nextLine() you receive "\\n", ie the Enter key.因此,当使用 input.nextLine() 读取下一行时,您会收到“\\n”,即Enter键。 So to skip this you have to add the input.nextLine().所以要跳过这个你必须添加 input.nextLine()。

Try it like that:像这样尝试:

 System.out.print("Insert a number: ");
 int number = input.nextInt();
 input.nextLine(); // This line you have to add (it consumes the \n character)
 System.out.print("Text1: ");
 String text1 = input.nextLine();
 System.out.print("Text2: ");
 String text2 = input.nextLine();

There are several ways to get input from the user.有几种方法可以从用户那里获取输入。 Here in this program we will take the Scanner class to achieve the task.在这个程序中,我们将使用 Scanner 类来完成任务。 This Scanner class comes under java.util , hence the first line of the program is import java.util.Scanner;这个 Scanner 类来自java.util ,因此程序的第一行是import java.util.Scanner; which allows the user to read values of various types in Java.它允许用户在 Java 中读取各种类型的值。 The import statement line should have to be in the first line the java program, and we proceed further for code. import 语句行应该在 java 程序的第一行,我们进一步处理代码。

in.nextInt(); // It just reads the numbers

in.nextLine(); // It get the String which user enters

To access methods in the Scanner class create a new scanner object as "in".要访问 Scanner 类中的方法,请创建一个新的扫描仪对象作为“in”。 Now we use one of its method, that is "next".现在我们使用它的一种方法,即“下一步”。 The "next" method gets the string of text that a user enters on the keyboard. “next”方法获取用户在键盘上输入的文本字符串。

Here I'm using in.nextLine();这里我使用in.nextLine(); to get the String which the user enters.获取用户输入的字符串。

import java.util.Scanner;

class GetInputFromUser {
    public static void main(String args[]) {
        int a;
        float b;
        String s;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string");
        s = in.nextLine();
        System.out.println("You entered string " + s);

        System.out.println("Enter an integer");
        a = in.nextInt();
        System.out.println("You entered integer " + a);

        System.out.println("Enter a float");
        b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}
import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] arguments){
        Scanner input = new Scanner(System.in);

        String username;
        double age;
        String gender;
        String marital_status;
        int telephone_number;

        // Allows a person to enter his/her name   
        Scanner one = new Scanner(System.in);
        System.out.println("Enter Name:" );  
        username = one.next();
        System.out.println("Name accepted " + username);

        // Allows a person to enter his/her age   
        Scanner two = new Scanner(System.in);
        System.out.println("Enter Age:" );  
        age = two.nextDouble();
        System.out.println("Age accepted " + age);

        // Allows a person to enter his/her gender  
        Scanner three = new Scanner(System.in);
        System.out.println("Enter Gender:" );  
        gender = three.next();
        System.out.println("Gender accepted " + gender);

        // Allows a person to enter his/her marital status
        Scanner four = new Scanner(System.in);
        System.out.println("Enter Marital status:" );  
        marital_status = four.next();
        System.out.println("Marital status accepted " + marital_status);

        // Allows a person to enter his/her telephone number
        Scanner five = new Scanner(System.in);
        System.out.println("Enter Telephone number:" );  
        telephone_number = five.nextInt();
        System.out.println("Telephone number accepted " + telephone_number);
    }
}

You can make a simple program to ask for the user's name and print whatever the reply use inputs.您可以制作一个简单的程序来询问用户的姓名并打印回复使用输入的任何内容。

Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.或者让用户输入两个数字,您可以将这些数字相加、相乘、相减或相除,然后打印用户输入的答案,就像计算器的行为一样。

So there you need the Scanner class.所以你需要 Scanner 类。 You have to import java.util.Scanner;你必须import java.util.Scanner; , and in the code you need to use: ,并在您需要使用的代码中:

Scanner input = new Scanner(System.in);

input is a variable name. input是一个变量名。

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value

System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer

System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double

See how this differs: input.next();看看有什么不同: input.next(); , i = input.nextInt(); , i = input.nextInt(); , d = input.nextDouble(); , d = input.nextDouble();

According to a String, int and a double varies the same way for the rest.根据字符串, int 和 double 以相同的方式变化。 Don't forget the import statement at the top of your code.不要忘记代码顶部的 import 语句。

A simple example:一个简单的例子:

import java.util.Scanner;

public class Example
{
    public static void main(String[] args)
    {
        int number1, number2, sum;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter First multiple");
        number1 = input.nextInt();

        System.out.println("Enter second multiple");
        number2 = input.nextInt();

        sum = number1 * number2;

        System.out.printf("The product of both number is %d", sum);
    }
}

When the user enters his/her username , check for valid entry also.当用户输入他/她的username ,还要检查输入是否有效。

java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name

System.out.print("Please enter the username: ");
userName = input.nextLine();

while(userName.length() < validLength) {

    // If the user enters less than validLength characters
    // ask for entering again
    System.out.println(
        "\nUsername needs to be " + validLength + " character long");

    System.out.print("\nPlease enter the username again: ");
    userName = input.nextLine();
}

System.out.println("Username is: " + userName);
import java.util.*;

class Ss
{
    int id, salary;
    String name;

   void Ss(int id, int salary, String name)
    {
        this.id = id;
        this.salary = salary;
        this.name = name;
    }

    void display()
    {
        System.out.println("The id of employee:" + id);
        System.out.println("The name of employye:" + name);
        System.out.println("The salary of employee:" + salary);
    }
}

class employee
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
        s.display();
    }
}

Here is the complete class which performs the required operation:这是执行所需操作的完整类:

import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        final int valid = 6;

        Scanner one = new Scanner(System.in);
        System.out.println("Enter your username: ");
        String s = one.nextLine();

        if (s.length() < valid) {
            System.out.println("Enter a valid username");
            System.out.println(
                "User name must contain " + valid + " characters");
            System.out.println("Enter again: ");
            s = one.nextLine();
        }

        System.out.println("Username accepted: " + s);

        Scanner two = new Scanner(System.in);
        System.out.println("Enter your age: ");
        int a = two.nextInt();
        System.out.println("Age accepted: " + a);

        Scanner three = new Scanner(System.in);
        System.out.println("Enter your sex: ");
        String sex = three.nextLine();
        System.out.println("Sex accepted: " + sex);
    }
}
  1. To read input:读取输入:

     Scanner scanner = new Scanner(System.in); String input = scanner.nextLine();
  2. To read input when you call a method with some arguments/parameters:在调用带有一些参数/参数的方法时读取输入:

     if (args.length != 2) { System.err.println("Utilizare: java Grep <fisier> <cuvant>"); System.exit(1); } try { grep(args[0], args[1]); } catch (IOException e) { System.out.println(e.getMessage()); }

There is a simple way to read from the console.有一种从控制台读取的简单方法。

Please find the below code:请找到以下代码:

import java.util.Scanner;

    public class ScannerDemo {

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);

            // Reading of Integer
            int number = sc.nextInt();

            // Reading of String
            String str = sc.next();
        }
    }

For a detailed understanding, please refer to the below documents.详细了解请参考以下文档。

Doc文件

Now let's talk about the detailed understanding of the Scanner class working:下面我们来详细了解一下Scanner类的工作原理:

public Scanner(InputStream source) {
    this(new InputStreamReader(source), WHITESPACE_PATTERN);
}

This is the constructor for creating the Scanner instance.这是用于创建 Scanner 实例的构造函数。

Here we are passing the InputStream reference which is nothing but a System.In .这里我们传递InputStream引用,它只是一个System.In Here it opens the InputStream Pipe for console input.在这里,它打开用于控制台输入的InputStream管道。

public InputStreamReader(InputStream in) {
    super(in);
    try {
        sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
    }
    catch (UnsupportedEncodingException e) {
        // The default encoding should always be available
        throw new Error(e);
    }
}

By passing the System.in this code will opens the socket for reading from console.通过在此代码中传递 System.in,将打开套接字以从控制台读取。

You can flow this code:您可以使用以下代码:

Scanner obj= new Scanner(System.in);
String s = obj.nextLine();

You can use the Scanner class in Java您可以使用 Java 中的 Scanner 类

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner;  // Import the Scanner class

class Main { // Main is the class name
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter username");

    String userName = myObj.nextLine();  // Read user input
    System.out.println("Username is: " + userName);  // Output user input
  }
}

you have wrote你写过

Scanner = input()

this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is这是错误的方法,你必须创建一个 integer 或一个字符串,我更喜欢字符串,然后给一个字符串任何名称,可以是 i 可以是 n 或其他任何名称,记住你给用户名你的名字也可以给出名称用户名,代码是

String username = sc.nextline();
System.our.println("the username is" + username);

I hope you understand now我希望你现在明白

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

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