JAVA學習腳印3: java語言控制流程

The fool發表於2014-04-08

JAVA學習腳印3: java語言控制流程

本節首先介紹,java語言中的字串處理以及輸入輸出控制,最後介紹控制流程。

 

在講述控制流程之前,先介紹以下java中字串和輸入輸出的內容,以便後續練習編寫控制流程程式時做準備。


1.字串處理

 

java中的字串就是uncoded字元序列。java標準庫提供了String類來處理字串。

1)構建字串

第一種方式就是使用雙引號把字串括起來,例如"hello"就是一個字串String類的一個例項:String greeting = "hello";

第二種方式是使用字串構建器StringBuilder類提供的方法。有些時候需要由較短的字串構建字串,這個時候使用字串連線符號+(見下面字串拼接部分)的效率比較低,因此可以使用StringBuilder類來避免該問題,例如:

StringBuilder builder = new StringBuilder();

builder.append("hello");

builder.append(",world!");

String hello = builder.toString();

System.out.println(hello);// print hello,world!

2)字串拼接

java語言使用+來實現字串的拼接,例如"hello"+",world!",將形成"hello,world!"。

注意,當將一個字串與一個非字串的值進行拼接時,後者將自動呼叫其toString()方法轉換為字串並與前者拼接在一起,例如:

"your age is "+age;//Ok

3)字串取子串

使用sustring方法,例如 hello=hello.substring(0,3)+'p';// hello = "help"

4)字串比較

使用equals方法檢測兩個字串是否相等,一定不能使用 == 運算子檢測兩個字串是否相等,== 運算子只能夠確定兩個字串是否放置在同一個位置上。

我們檢視String類equals方法原始碼:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

就明白了equals方法將首先檢視是否引用同一個物件,若是則肯定兩個字串物件相等;否則逐個字元的比較兩個物件,直到判斷出結果。

String a = "hello";
String b = "hello";
String c = "help";
System.out.println((a == b));// pirnt true
System.out.println( ("hel" == c.substring(0,3)) );//print false
System.out.println((a.equals(b)));//print true
System.out.println((a.equals(c)));//print false

實際上虛擬機器中字串常量是共享的,所以a==b 為true;但是+或者substring等操作產生的結果並不是共享的,因此"hel" == c.substring(0,3)) 為false。

因此不要使用 == 運算子檢測字串是否相等,而要使用使用equals方法。

2.輸入輸出

 

1)標準輸入輸出流(控制檯視窗)

輸入:

首先構造一個Scanner物件來關聯System.in,接受輸入:

Scanner in = new Scanner(System.in);

String name = in.nextLine();//輸入姓名

int age = in.nextInt();// 輸入年齡

另外從控制檯讀取密碼時一般會回顯出來,因此係統提供了Console類提供密碼輸入:

Console cons;
String username;
char[] passwd;
if ((cons = System.console()) != null) {
	username = cons.readLine("User name:");
	passwd = cons.readPassword("Password:");
	//do some job
	Arrays.fill(passwd, ' ');//迅速填充密碼域 避免資訊洩漏
}

輸出:

輸出基本上時之前經常用過的了,如System.out.print。要想格式化輸出,java提供了和C語言一樣的System.out.printf函式來控制輸出格式。當然也可以使用靜態的String.format方法建立一個格式化的字串用於輸出,例如:

System.out.printf("%.8f", Math.PI);// print 3.14159265

 

2)檔案的輸入輸出

輸入:

同樣可以利用Scanner來讀入檔案,例如:

Scanner in = new Scanner(new File("1.txt"));

String line = in.nextLine();

輸出:

可以利用PrintWriter來寫入檔案,例如:

PrintWriter out = new PrintWriter(new File("2.txt"));

out.println(line);

注意Scanner和PrintWriter建構函式均需要File物件,File物件表達的是抽象路徑名,它根據路徑字串生成。

下面綜合標準輸入輸出流以及檔案讀寫流,編寫一個從控制檯讀入檔名,然後讀取檔案內容,並將檔案行數寫入檔案及控制檯的程式。程式碼如下例3-1所示:

3-1  InputAndOutput.java

package com.learningjava;
import java.io.*;
import java.util.Scanner;

/**
 * a program to statistic file line count
 * @version 1.1 2013-08-06
 * @author wangdq
 */
public class InputAndOutput {
	public static void main(String[] args) {
		 try {
			 //read file name form standard input
			Scanner in = new Scanner(System.in);
			
			//constuct a new scanner to read file
			System.out.println("input the filename for reading content:");
			Scanner filein = new Scanner(new File(in.nextLine ()));
			
			//construc a new writer to write file
			System.out.println("input the filename for storing result:");
			PrintWriter out = new PrintWriter(new File(in.nextLine()));
			
			//read lines from file
			int lineCnt = 0;
			while(filein.hasNextLine()) {
				filein.nextLine();
				lineCnt++;
			}
			
			//store the lineCnt to the file
			out.println("there has :"+lineCnt+" in the file.");
			//print the lineCnt to the standard output
			System.out.println(lineCnt);
			
			//close the stream
			in.close();
			filein.close();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

程式執行效果:

wangdq@wangdq:~/workspace/InputAndOutput/bin$ java com.learningjava.InputAndOutput

input the filename for reading content:

../src/com/learningjava/InputAndOutput.java

input the filename for storing result:

../cnt.txt

45

wangdq@wangdq:~/workspace/InputAndOutput/bin$ cat ../cnt.txt

there has :45 in the file.

程式讀取InputAndOutput.java檔案,計算出公有45行,並將結果寫到cnt.txt檔案中,顯示在控制檯上。linux 下可通過 cat filename|wc -l 命令或者利用vim編輯器檢視檔案行數,以驗證程式的正確性。

3.流程控制

 

java中流程控制與c++中基本上相同,但也有區別。java中分支結構可以由if、或者if...else語句控制 ,多重選擇由switch語句實現;迴圈結構一共有三種即while、do...while、for迴圈;中斷流程的語句有break和continue語句。

需要注意的是:

1)在java中不允許在巢狀的塊中重定義一個變數。例如:

int n = 0;
int m = 5;
for(int n = 0 ;n< m;n++) {	
}

將出現錯誤:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Duplicate local variable n

外圍的變數n和for迴圈塊中的n屬於重複定義。再看一例,語句序列:

int n = 0;
int m = 5;
if(m > 0){
     int n;
}

也會引起同樣的問題,注意java與c++的區別。

2)java中還新增了一種更好的迴圈結構,這種增強的迴圈結構語句格式如下:

for(variable: collection) statement 

例如輸出陣列的內容可以如下:

String[] words = {"apple","banana","orange","grape"};
for(String item:words) {
	System.out.println(item);
}

可以將這種迴圈稱之為for each迴圈,它使程式碼更加簡潔。



至此,熟悉了java語言中的字串,輸入輸出以及控制流。

相關文章