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

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

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


当前回答

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 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.*;

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