zoukankan      html  css  js  c++  java
  • java--从控制台读入一些数据

    学一些东西应该,学以致用:

    现在我开始使用流的办法从控制台读取数据

    import java.io.*;
    
    public class Demo2{
        public static void main(String[] args) throws IOException{
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String string = in.readLine();
            double n = Double.parseDouble(string);
            System.out.println(n);
            
        }
    }

    首先,要创建一个流,来读取数据,BufferedReader in  = new BufferedReader(new InputStreamReader(System.in));

    你所要读取的数据现在已经在缓冲区内了,现在的任务就是要从这个区域中读取出来。

    String string = in.readLine();

    读来的数据是以字符串的格式保存的,所以为了以后使用这个数据,还要将这个数据转换为适当的格式。

    int n = Integer.parseInt(string);//在之前的一些博客中已经介绍了//

    这样就可使用这个数据了。

    二、Scanner方法:

    Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。

    Scaner 将获得数据按照规定的格式进行分解(默认状态下是空格);

    以下代码使用户能够从 System.in 中读取一个数:

         Scanner sc = new Scanner(System.in);
         int i = sc.nextInt();
    

    Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
    所以在这种情况下也可以在控制台读入数据。
  • 相关阅读:
    51nod 1081 子段求和
    51nod 1085 背包问题
    51nod 1012 最小公倍数LCM
    51nod 1046 A^B Mod C
    51nod 1057 N的阶乘
    死锁 必然
    two-sum
    一些基本定义
    常用命令
    python_99_面向对象多态
  • 原文地址:https://www.cnblogs.com/plxx/p/3415690.html
Copyright © 2011-2022 走看看