Java基础知识之Scanner类的用法

Scanner 类的主要方法:

        nextLine():String  返回读取的字符串

        nextInt():Int   返回读取的整形数据

        nextDouble():Double  返回读取的double类型数据

        其他同型方法以此类推;

        hasNext():boolean  判断是否还有下一个数据

        next():Object 获取下一个数据

        这两个方法主要用来遍历。

一.扫描控制台输入

public class ScannerTest
{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in);
        System.out.println("What's your name?");
        String name = s.nextLine();
        System.out.println("How old are you?");
        int age = s.nextInt();
        
        System.out.println("Welcome," + name + ",next year you will be " + (age +1)  + " years old !");
    }
}

二.读取文件

public class ScannerTest2{
    public static void main(String args[]){
        File file = new File("d:" + File.seperator + "test.txt");
        InputStream is = new FileInputStream(file);
        Scanner s = new Scanner(is);
        while(s.hasNext()){
            System.out.println(s.next());
        }
        s.close();
    }
}

问题:我试着用了另外一种读取文件的方式但是读不出来,没有找出原因,读者如果找到原因的话 麻烦告知我,在此谢谢。先贴出错误代码:

public class ScannerTest3{
    public static void main(String args[]){
        File file = new File("d:" + File.seperator + "test.txt");
        Scanner s = new Scanner(file);
        while(s.hasnext()){
            System.out.println(s.next());
        }
    }
}

Scanner类是有这个构造函数的: Scanner  Scanner(File file),按理说上面的代码应该是没问题的,但是却读不出test.txt文件的内容。

三.读取字符串内容

public class ScannerTest4{
    public static void main(String args[]){
        Scanner s = new Scanner("hello world I love you");
        while(s.hasnext()){
            System.out.println(s.next());
        }
    }
}



输出结果为:

hello
world
I
love
you

上面的代码采用默认的Pattern来分割字符串,还可以指定分割模式:

public class ScannerTest5{
    public static void main(String args[]){
        Scanner s = new Scanner("Hello,world,I,love,you");
        s.useDelimiter(",");
        while(s.hasnext()){
            System.out.println(s.next());
        }
    }
}

输出结果同上。

猜你喜欢

转载自blog.csdn.net/lintiyan/article/details/82980754