【Java】_2_Java程式入門第二課

來源:互聯網
上載者:User

  前面一課說了簡單的整型資料和浮點型資料,但是沒有說char字元類型,今天我們來說說char字元類型。

【Java  Char型】

  在Java中提供了字元類型,與C/C++類似,Java中字元是經過編碼的;Exp: 編碼值==65的字元是'A';

在Java中,使用的是Unicode編碼格式。通常情況下,我們認為Unicode是16 bit的編碼規則。

  但是很多童鞋們,還是不明白這個東西,我自己也有點迷糊。下面是我摘錄的部分度娘知道的回答:

     如果按照編碼規則來看,這個賦值是相容的。 輸出的時候系統是根據“數值”的類型來判斷的,正如上面說的,當用

System.out.println(numchar+4);

     這裡會輸出的是什麼呢?我們可以看一下:

/*This program try to test the CHAR data type*/public class CharTest{  public static void main(String[] args)   {    char charTestVar=4;             System.out.println(charTestVar+4);   }}

輸出如下所示:

 

而下面的程式段:

/*This program try to test the CHAR data type*/public class CharTest{  public static void main(String[] args)   {    char charTestVar=4;             System.out.println(charTestVar+4);             System.out.println(charTestVar);   }}

輸出如下所示:

  這是為什麼呢?我們知道在運算式計算過程中:會進行類型轉換,通常是向數值範圍方向大的轉;因此第一段代碼輸出是8,而第二段代碼輸出的是8和四方形。

 

【Java 控制台輸入資料流】

  在Java類庫中System.out 類在java.lang包中定義,這是一個預設包含的包。而在Java中輸出資料不是這樣的,在需要從控制台輸入資料的時候,則需要

引用Java提供的類庫包,這個與C語言一樣(C語言通過系統提供的庫函數實現輸入和輸出)。

  在Java中用Scanner可以實現控制台資料的輸入,Scanner是一個類,通過類的建構函式構造對象,然後通過類的方法(類似C++中的成員函數)來實現

資料的讀取。

  構造Scanner對象文法:   Scanner   objectIdentify=new  Scanner(System.in);

     在使用這個類的時候需要匯入: java.util包,其文法如下:

 import  java.util.*;

  這裡需要注意一點:因為import是完整的java語句,因此後面的分號不能少。

  下面我們看一段簡單的代碼如何?資料的輸入:

/*This program test scaner */import java.util.*;public class ScanerIn{  public  static void main(String[] args)   {      Scanner GetData=new Scanner(System.in);              System.out.print("Please enter you name:");              System.out.println("You name is:"+GetData.nextLine());   }}

  這段代碼執行的結果如下所示:

  Scanner對象提供了很多不同的方法來輸入不同的資料類型:

    1、Scanner (InputStream In)

      用給定的輸入資料流建立一個Scanner對象

    2、String nextLine()

      讀取輸入的下一行內容,並儲存為String對象

    3、String next()

      讀取輸入的下一個單詞,單詞以空白符分隔,空格、定位字元算空白符(blank charecter)

    4、int  nextInt()

      讀取輸入的下一個整型數值

    5、doublet nextDouble()

      讀取輸入的下一個浮點數值

    6、boolean  hasNext()

      檢測輸入資料流中是否還有其他單詞

    7、boolean  hasNextInt()

      檢測輸入資料流中是否還有整數

    8、boolean  hasDouble()

      檢測輸入資料流中是否還有浮點數值

下面我來測試一下這寫類的方法:

/*This program test scaner */import java.util.*;public class ScanerIn{  public  static void main(String[] args)   {      Scanner GetData=new Scanner(System.in);              System.out.print("Please enter you name:");              System.out.println("You name is:"+GetData.nextLine());                System.out.print("Now we have got you name,Can we get you age:");              System.out.println("Your age is:"+GetData.nextInt());              System.out.print("Can you show the expect salary:");              System.out.println("Your expect salary is:"+GetData.nextDouble());     if(GetData.hasNext())        System.out.println("You hava finish you input data!!!");   }}

  程式執行過程如下所示:

  

  這裡我有一點迷惑?那就要if子句執行過程和我想象的不一樣。

 【Java 控制台密碼輸入】

  如上面的測試一樣,我們知道,在console輸入中利用Scanner對象輸入的時候,是明文輸入的,有時候我們需要輸入密碼,很顯然,密碼不能用明文

進行輸入,否則就失去了保密的作用;考慮這一點,Java提供了另外一種輸入方式來實現密碼的輸入。

  在Java中利用Console類實現密碼的輸入。其使用方法如下:

  //首先利用Console類構造一個對象

  Console   CodeInput=System.console

  String      UserName=CodeInput.readLine();

  String      PassWord=CodeInput.readPassword();

  執行個體代碼如下所示:

    Console CodeInput=System.console();    String UserName;    char[] Password;           UserName=CodeInput.readLine("Enter your name:");           Password=CodeInput.readPassword("Enter the password:");    

  這段代碼執行過程如所示:

  這樣的話,明文就不顯示,並且Java繼承了Unix/Linux的特徵在輸入密碼的時候不顯示*或者其他掩碼符號。

  這裡有一點需要注意:如果要使用Console類,必須匯入java.io.Console; 否則不能使用;同時object.readPassword()方法返回的值是數群組類型,不能用String對象

儲存,否則會報錯。如下所示:

 

【Java 讀取檔案內容】

  和其他程式設計語言一樣,Java也提供了讀寫檔案的機制,與C語言不一樣的是,C語言讀寫檔案非常麻煩,而在Java中通過前面所介紹的Scanner對象就可以實現檔案的讀寫。

在使用前需要構造Scanner檔案對象。如下所示:

  Scanner    FileIn=new Scanner(new File("test.txt"));

  這樣就構造了一個檔案輸入輸出對象,通過Scanner檔案對象就可以進行檔案的讀寫。

  為了防止檔案讀寫“指標”無指向,在檔案讀寫語句中,必須進行異常捕捉;否則在編譯的過程中會報沒有進行異常處理。 

 

  因為異常類型的處理我還沒有深入瞭解,因此這裡就不多說了,以後有機會再說。

  下面我沒來看一下檔案讀取的代碼:

/*This program test scaner */import java.util.*;import java.io.Console;import java.io.File;public class ScanerIn{  public  static void main(String[] args)   {    /*    //Scanner 對象測試    Scanner GetData=new Scanner(System.in);              System.out.print("Please enter you name:");              System.out.println("You name is:"+GetData.nextLine());                System.out.print("Now we have got you name,Can we get you age:");              System.out.println("Your age is:"+GetData.nextInt());              System.out.print("Can you show the expect salary:");              System.out.println("Your expect salary is:"+GetData.nextDouble());        //Console對象測試    Console CodeInput=System.console();    String UserName;    char[] Password;           UserName=CodeInput.readLine("Enter your name:");           Password=CodeInput.readPassword("Enter the password:");    */        //File對象測試    try    {    Scanner FileIn=new Scanner(new File("TestText.txt"));        while(FileIn.hasNext())            System.out.println(FileIn.nextLine());    }catch(Exception e)     {         System.out.println(e);     }        /*    if(!GetData.hasNext())           System.out.println("You hava finish you input data!!!");    */   }}

  這個代碼的執行過程如下所示:

  仔細看上面的執行過程可以發現,如果沒有檔案我們就不能讀取檔案,報檔案找不到的異常,要是不用try結構捕捉的話,那麼我們的程式運行過程中就會崩潰。如果

沒有檔案:TextText.txt,執行結果就如下所示:

  可以看到Scanner對象,不能建立檔案,那麼我麼要如何建立檔案呢?這個就等到下次再來說吧,我們再來看看檔案的寫入。

【Java 寫內容到檔案】

  在Java中寫檔案和讀取檔案內容一樣容易實現。

  為了實現“寫”檔案,我們需要構造一個PrintWriter對象;如下所示:

  PrintWriter  FileOut=new PrintWriter("filename.txt");

  這個對象需要引用java.io.PrinterWriter對象,為了省略很多的引用,通常我們引用:

          java.io.*;  

     即可,但是我建議在不熟悉的時候,引用什麼對象,則匯入不同的對象,這樣可以增加對類庫的認識。

  我們來看一段執行個體代碼:

/*This program test scaner */import java.util.*;import java.io.Console;import java.io.File;import java.io.PrintWriter;import java.io.*;public class ScanerIn{  public  static void main(String[] args)   {    /*    //Scanner 對象測試    Scanner GetData=new Scanner(System.in);              System.out.print("Please enter you name:");              System.out.println("You name is:"+GetData.nextLine());                System.out.print("Now we have got you name,Can we get you age:");              System.out.println("Your age is:"+GetData.nextInt());              System.out.print("Can you show the expect salary:");              System.out.println("Your expect salary is:"+GetData.nextDouble());        //Console對象測試    Console CodeInput=System.console();    String UserName;    char[] Password;           UserName=CodeInput.readLine("Enter your name:");           Password=CodeInput.readPassword("Enter the password:");    */                   /******************    //File對象測試    try    {    Scanner FileIn=new Scanner(new File("TestText.txt"));        while(FileIn.hasNext())            System.out.println(FileIn.nextLine());    }catch(Exception e)     {         System.out.println(e);     }    **************/    //寫檔案測試    try    {    PrintWriter FileOut=new PrintWriter(new FileWriter("TestText.txt"));        FileOut.println("Hello wellcome to my word");        FileOut.println("This is my fisrt to write a file via java");        FileOut.println(":)");                FileOut.close();    }catch(Exception e)     {         System.out.println(e);     }        //測試寫入檔案是否成功,還測試,改寫是追加還是全部重寫         try    {    Scanner FileIn=new Scanner(new File("TestText.txt"));        while(FileIn.hasNext())            System.out.println(FileIn.nextLine());    }catch(Exception e)     {         System.out.println(e);     }        /*    if(!GetData.hasNext())           System.out.println("You hava finish you input data!!!");    */   }}

  上面代碼的執行結果如下:

  這裡可以看到程式成功執行了。要點: 我們可以看到重複的匯入庫是不會報錯的。

  而且這樣的寫入檔案時全部覆蓋,會將原來的檔案全部覆蓋掉。如果不能覆蓋原來的內容,則需要進行處理;我搜到了一段代碼如下,可供大家參考:

import java.io.*;import java.util.*;public class TestPrintWriter{    public static void main(String[] args)throws IOException     {           File file=new File("temp2.txt");                if(file.exists())                {                   System.out.println("File temp.txt already exists.");                   System.exit(0);                }           PrintWriter output=new PrintWriter(new FileWriter(file));                   for(int i=0;i<10;i++)                   {            output.print((int)(Math.random()*100)+" ");           }        output.close();        BufferedReader input=new BufferedReader(new FileReader("temp2.txt"));        int total=0;        String line;        while((line=input.readLine())!=null)        {           StringTokenizer tokens=new StringTokenizer(line);           while(tokens.hasMoreTokens())           total+=Integer.parseInt(tokens.nextToken());        }                output=new PrintWriter(new FileWriter(file,true));        output.printf("\n\n");        output.printf("Total is %d ",total);        output.close();    }}

 

今天就寫到這裡了,希望這次可以將這本書從頭看到尾,然後根據學習進度寫完整本書的總結。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.