Scanner类

Scanner类

创建Scanner对象

  1. 从键盘读取
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
  1. 从字符串读取
Scanner sc = new Scanner("Hello World 123");
  1. 从文件读取
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

try {
    Scanner sc = new Scanner(new File("data.txt"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

常用方法分类

判断是否有下一个输入

  • hasNext()
  • hasNextInt()
  • hasNextDouble()
  • hasNextLine()

读取输入

  • next() 读取下一个token
  • nextInt() 读取下一个整数
  • nextDouble() 读取下一个浮点数
  • nextLine()
  • nextBoolean()
  • nextLong()
  • nextshort()
  • nextByte()
  • nextFloat()
posted @ 2026-01-29 21:05  张张312  阅读(0)  评论(0)    收藏  举报