java如何获取用户的输入
利用Scanner类,来获取用户的输入
// 导入所需要的类
import java.util.Scanner;
public class GetUserInput {
public static void main(String[] args) {
/*
* nextLine() 与 next() 的区别
* 输入"hello world!",比较输出的结果,得出以下结论:
* nextLine():以 Enter(回车) 为结束符
* next():不会获得带有空白(空格)的字符串,如:"hello world!"中只能获得"hello"
*/
// 创建对象
Scanner scanner = new Scanner(System.in);
// nextLine()
// 存放获取的字符串
String str1 = "";
System.out.print("用nextLine()获取用户的输入,请输入:");
// 判断是否还有字符串输入
if (scanner.hasNextLine()) {
// 获取输入的字符串,以 Enter(回车) 为结束符
str1 = scanner.nextLine();
}
System.out.println("你输入的内容为:" + str1);
// 分割线
System.out.println("-------------------------------------------");
// next()
// 存放获取的字符串
String str2 = "";
System.out.print("用next()获取用户的输入,请输入:");
// 判断是否还有字符串输入
if (scanner.hasNext()) {
// 获取输入的字符串,不会获得带有空白(空格)的字符串
str2 = scanner.next();
}
System.out.println("你输入的内容为:" + str2);
// 如果不关闭就会一直占用资源,要养成良好的习惯用完就关掉
scanner.close();
}
}
运行结果: