如何使用Scanner
类从控制台读取输入?如下所示:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
基本上,我想要的就是让扫描程序读取用户名的输入,并将输入赋给一个String
变量。
发布于 2012-08-09 03:29:23
从System.in
读取一个整数就是一个简单的例子来说明java.util.Scanner
是如何工作的。这真的很简单。
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);
如果希望更好地控制输入,或者只验证username
变量,也可以使用next(String pattern)
。
您将在API Documentation for java.util.Scanner
中找到有关其实现的更多信息
发布于 2012-08-09 03:15:38
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
发布于 2013-08-20 18:45:54
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);
}
}
https://stackoverflow.com/questions/11871520
复制相似问题