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(); }
所以在这种情况下也可以在控制台读入数据。
posted @ 2013-11-09 15:35  平林新袖  阅读(597)  评论(0编辑  收藏  举报