java基本輸入輸出練習

    java獲取用戶的輸入分兩種,一種是字符的輸入,一種是整行的輸入,要用到java.io包。對於字符輸入來講,使用System.in方法能夠輸入字符;對於整行的輸入,能夠使用Scanner類的方法獲取整行輸入。java

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掃描器除上述讀入輸入流一行功能外,有如下幾種用法:web

    (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)用於掃描字符串或文件,利用分隔符作處理。默認使用空格作分隔符,但也能夠重定義分隔符。註釋行表示使用空格、逗號或點號作分隔符。spa

    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)逐行掃描文件並逐行輸出code

        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()); 
                } 
        }
相關文章
相關標籤/搜索