java基本输入输出练习

    java获取用户的输入分两种,一种是字符的输入,一种是整行的输入,要用到java.io包。对于字符输入来说,使用System.in方法可以输入字符;对于整行的输入,可以使用Scanner类的方法获取整行输入。

import java.io.*;
import java.util.*;
public class helloWorld {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char c = '3';
        System.out.print("hello world,please read in a character:");
        try{
            //只能读取输入的一个字母
            c=(char)System.in.read();
        }catch(IOException e){}
        System.out.println("entered:" + c);        
        String s = "";
        System.out.println("please read in a line:");
        //读取输入的一行
        //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        Scanner in = new Scanner(System.in);
        s = in.next();
        System.out.println("entered" + s);        
        }
}

    Scanner是一个使用正则表达式来解析基本类型和字符串的文本扫描器。Scanner扫描器除上述读入输入流一行功能外,有以下几种用法:

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

        int test;
        Scanner sc = new Scanner(System.in);
        test = sc.nextInt();
        System.out.println("have entered a int:" + test);
        double test1;
        Scanner sc1 = new Scanner(System.in);
        test1 = sc1.nextDouble();
        System.out.println("have entered a double:" + test1);

    (2)用于扫描字符串或文件,利用分隔符做处理。默认使用空格做分隔符,但也可以重定义分隔符。注释行表示使用空格、逗号或点号做分隔符。

    Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las"); 
    //s.useDelimiter(" |,|\."); 
    while (s.hasNext()) { 
        System.out.println(s.next()); 
    }        

    (3)逐行扫描文件并逐行输出

        public static void main(String[] args) throws FileNotFoundException { 
                InputStream in = new FileInputStream(new File("C:\AutoSubmit.java")); 
                Scanner s = new Scanner(in); 
                while(s.hasNextLine()){ 
                        System.out.println(s.nextLine()); 
                } 
        }
原文地址:https://www.cnblogs.com/north-north/p/3770520.html