010 输入流Scanner

输入流

类Scanner

常用方法

  • next() //对输入前后空格会自动去掉,只去第一个字符串
  • hasNext()
  • nextLine() //获取回车前的输入的所有字符
  • hasNextLine()
  • close()
  • hasNextInt()
  • nextInt()
    等等

调用完可关闭避免占用系统资源

eg:next

public class Interaction {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用next接收:");
        if (scanner.hasNext()) {
            String str = scanner.next();
            System.out.println("next:" + str);    //str在if块中定义,所以作用在该块中
        }
        scanner.close();
    }
}

eg:nextline

public class Interaction {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("使用nextline接收:");
        if (scanner.hasNextLine()) {
            String str = scanner.nextLine();
            System.out.println("nextline:" + str);
        }
        scanner.close();
    }
}
posted @ 2020-09-29 11:17  Jelle  阅读(98)  评论(0)    收藏  举报