如何使用Scanner类从控制台读取输入?就像这样:

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

基本上,我想要的只是让扫描器读取用户名的输入,并将输入分配给一个String变量。


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

说明java.util.Scanner如何工作的一个简单示例是从System.in中读取单个整数。这真的很简单。

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

要检索用户名,我可能会使用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);

如果您想对输入进行更多控制,或者只是验证用户名变量,也可以使用next(字符串模式)。

你可以在java.util.Scanner的API文档中找到更多关于它们实现的信息


当用户输入他/她的用户名时,也检查是否有有效的输入。

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

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

您可以编写一个简单的程序来询问用户的姓名,并打印任何回复使用的输入。

或者要求用户输入两个数字,您可以对这些数字进行加、乘、减或除,并像计算器一样打印用户输入的答案。

这里你需要Scanner类。你必须导入java.util.Scanner;,并且在你需要使用的代码中:

Scanner input = new Scanner(System.in);

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

看看这有什么不同:input.next();, i = input.nextInt();, d = input.nextDouble();

根据String类型,int类型和double类型的变化方式与其他类型相同。不要忘记代码顶部的import语句。


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

下面是执行所需操作的完整类:

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

读取输入: 扫描仪扫描仪=新的扫描仪(System.in); 字符串输入= scanner.nextLine(); 当你调用一个带有参数/形参的方法时读取输入: 如果(arg游戏。长度!= 2){ System.err。println(" utilzare: java Grep < filier > <cuvant>"); system . exit (1); } 尝试{ grep (args [0], arg游戏[1]); } catch (IOException e) { System.out.println (e.getMessage ()); }


从控制台读取数据

BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes. readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \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. « 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. « A scanner however is not thread safe. It has to be externally synchronized. next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an 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);
}

流的输入和输出

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

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

有几种方法可以从用户那里获得输入。在这个程序中,我们将使用Scanner类来完成任务。这个Scanner类属于java。util,因此程序的第一行是import java.util.Scanner;它允许用户读取Java中各种类型的值。import语句行必须在java程序的第一行中,我们将进一步处理代码。

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

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

为了访问Scanner类中的方法,创建一个新的Scanner对象作为“in”。现在我们用它的一种方法,那就是“next”。“next”方法获取用户在键盘上输入的文本字符串。

这里我使用in.nextLine();来获取用户输入的字符串。

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

你可以在Java中使用Scanner类

Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);

有一种从控制台读取的简单方法。

请查看以下代码:

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

具体理解请参考以下文件。

Doc

现在我们来详细了解一下Scanner类的工作原理:

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

这是用于创建Scanner实例的构造函数。

这里我们传递的是InputStream引用,它只是一个System.In。在这里,它打开了用于控制台输入的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);
    }
}

通过系统。在这段代码中,将打开套接字以从控制台读取。


你可以流动这段代码:

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

input.nextInt()方法有问题——它只读取int值。

因此,当使用input.nextLine()读取下一行时,您会收到“\n”,即回车键。所以要跳过这个,你必须添加input.nextLine()。

试着这样做:

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

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
  }
}

你写过

Scanner = input()

这是错误的方法,你必须创建一个整数或字符串,我更喜欢字符串,然后给一个字符串任意的名字,可以是I可以是n,或者其他的,记住你是在给用户名取名字你也可以给名字取用户名,代码是

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

我希望你现在明白了