java基础-scanner使用
scanner类使用
-
Scanner类和String类一样是一个最终类,public final class Scanner
-
Scanner类使用new关键字创建Scanner实例,需要给构造函数传入System.in
Scanner sc = new Scanner(System.in);
-
Scanner类使用nextXxx()接收从键盘输入的各种类型的值
//使用scanner从键盘接首int值 int i = sc.nextInt();
-
Scanner类还能从文件读取输入
public static void main(String[] args) throws Exception { Scanner sc = new Scanner(new File("sc.txt")); while (sc.hasNext()){ System.out.println(sc.nextLine()); } sc.close(); }
-
next()和nextline()的区别
- next():读取输入时遇到空白时会停止读取之后的字符,即是后面还有
- nextline():读取输入时会读取一整行,直到遇到回车符