• Java基础知识强化之IO流笔记62:三种方式实现键盘录入


    1. 三种方式实现键盘录入

        System.in 标准输入流。是从键盘获取数据的

    键盘录入数据三种方式
           A:main方法的args接收参数。
               java HelloWorld hello world java
           BScanner(JDK5以后的)
               Scanner sc = new Scanner(System.in);
               String s = sc.nextLine();
               int x = sc.nextInt()
           C通过字符缓冲流包装标准输入流实现
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    2. 代码实现:

     1 package cn.itcast_04;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.IOException;
     5 import java.io.InputStreamReader;
     6 
     7 /*
     8  * System.in 标准输入流。是从键盘获取数据的
     9  * 
    10  * 键盘录入数据:
    11  *         A:main方法的args接收参数。
    12  *             java HelloWorld hello world java
    13  *         B:Scanner(JDK5以后的)
    14  *             Scanner sc = new Scanner(System.in);
    15  *             String s = sc.nextLine();
    16  *             int x = sc.nextInt()
    17  *         C:通过字符缓冲流包装标准输入流实现
    18  *             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    19  */
    20 public class SystemInDemo {
    21     public static void main(String[] args) throws IOException {
    22         // //获取标准输入流
    23         // InputStream is = System.in;
    24         // //我要一次获取一行行不行呢?
    25         // //行。
    26         // //怎么实现呢?
    27         // //要想实现,首先你得知道一次读取一行数据的方法是哪个呢?
    28         // //readLine()
    29         // //而这个方法在哪个类中呢?
    30         // //BufferedReader
    31         // //所以,你这次应该创建BufferedReader的对象,但是底层还是的使用标准输入流
    32         // // BufferedReader br = new BufferedReader(is);
    33         // //按照我们的推想,现在应该可以了,但是却报错了
    34         // //原因是:字符缓冲流只能针对字符流操作,而你现在是字节流,所以不能是用?
    35         // //那么,我还就想使用了,请大家给我一个解决方案?
    36         // //把字节流转换为字符流,然后在通过字符缓冲流操作
    37         // InputStreamReader isr = new InputStreamReader(is);
    38         // BufferedReader br= new BufferedReader(isr);
    39         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    40 
    41         System.out.println("请输入一个字符串:");
    42         String line = br.readLine();
    43         System.out.println("你输入的字符串是:" + line);
    44 
    45         System.out.println("请输入一个整数:");
    46         // int i = Integer.parseInt(br.readLine());
    47         line = br.readLine();
    48         int i = Integer.parseInt(line);
    49         System.out.println("你输入的整数是:" + i);
    50     }
    51 }

    运行效果,如下:

  • 相关阅读:
    LeetCode 152. 乘积最大子数组 | Python
    LeetCode 31. 下一个排列 | Python
    LeetCode 136. 只出现一次的数字 | Python
    LeetCode 102. 二叉树的层序遍历 | Python
    LeetCode 155. 最小栈 | Python
    LeetCode 69. x 的平方根 | Python
    Python3 高阶函数
    Python3 装饰器
    Python3 递归函数
    Python3 函数
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4872202.html
Copyright © 2020-2023  润新知