zoukankan      html  css  js  c++  java
  • java从键盘获取输入--scanner类

    平常工作中较少与键盘进行直接交互,但在一些测试方法中,需要有这样的功能。

    一、可以用System.in.read()方法读取单个字符,但因为字符大小的限制,实际使用中有很多不方便的地方。

    示例:

    char a = (char) System.in.read();
    System.out.println(a);

    需注意返回的是字符对应的ASCII码。要使用需要进行进一步处理。

    二、可以将控制台输入的当做字符串处理,需要使用BufferedReader类以及InputStreamReader类。

    示例:

    BufferedReader strBufferedReader = new BufferedReader(new InputStreamReader(System.in));
    String strString = strBufferedReader.readLine();
    System.out.println(strString);

    需注意用readLine()时,可以接收空格和tab,因此不能用空格和tab作为两个数之间的分割。

    三、使用Scanner类

    Scanner类非常强大,提供了读取基本类型的读取,同时nextLine()方法提供了字符串的获取。

    Scanner aaScanner = new Scanner(System.in);
    int a = aaScanner.nextInt();
    System.out.println("111_"+a);
    String strString = aaScanner.nextLine();
    System.out.println("aaa"+strString);
    String strString1 = aaScanner.nextLine();
    System.out.println("bbb"+strString1);

    需要注意的是,这里的nextLine()是可以接收回车的,在写程序的过程中,需要注意回车被接收到的情况。

  • 相关阅读:
    Solidity notes
    Solidity by Example详解
    基本命令中部
    基本命令上部
    服务器介绍
    Linux发展史及安装
    ERROR: Unrecognized command line argument: 'use'
    RequireJs 深入理解
    Redis 安装教程 (Windows 2.6.13 稳定版)
    System.AccessViolationException: 尝试读取或写入受保护的内存 解决办法
  • 原文地址:https://www.cnblogs.com/wee616/p/4815737.html
Copyright © 2011-2022 走看看