首頁  >  文章  >  Java  >  java幾種常見錯誤介紹

java幾種常見錯誤介紹

尚
原創
2019-12-23 15:43:284542瀏覽

java幾種常見錯誤介紹

java常見錯誤:

1、空指標錯誤

在java陣列的使用中,有時候需要對字串陣列中的元素進行對比。那麼當元素不為null時,程式會正常運作;然而,一旦對比的元素為null,那麼程式就會出現空指標錯誤。

解決方法:加入保護,當元素不為null時在進行判斷。

public static void main(Sring[] args){
  String [] sums = "adfafA";
  for(int i=0;i<sums.length;i++){
    if(sums[]!=null && sums[i].equals(sr)){
      System.out.println("找到元素"+sums[i]);
      break;
    }
  }
}

2、資料的精確度範圍與型別轉換

在Java中有4種基礎型別資料:

整數:  -1 2 3 4 …

浮點型:float 1.3f ;  double 3.2   3.5d (未標示類型,預設最高精確度)

字元型:採用Unicode編碼,2位元組

布林型: true、false

四種基礎類型資料的精確度範圍各不相同,逐級提升。

如果在使用資料類型時,不注意精度範圍,就會出現資料溢出,從而發生計算錯誤。

四種基礎類型中,整型,浮點型和字元型資料是可以相互轉換的。

轉換規則如下:

①隱形轉換:精度小的資料值,賦值給精度大的值,可以自動轉換。 (低階向進階)

②強制轉換:範圍大的資料值,(進階到低階)

③運算自動提升規則:運算中,自動轉換為精確度高的資料型別。

3、三種循環的使用

①for 循環:是一種有限次數的循環,在循環前,規定好循環次數。

for(表达式;表达式;表达式){
        循环体
 }

break語句:執行後,立即跳出循環,不在執行後面的語句,且結束所有循環。

continue 語句:執行後,立即跳出目前單字循環,重新判斷條件是否繼續循。

②While迴圈語句:適合未知次數的迴圈。

while(条件表达式){
  语句
 };

③do-While迴圈:也是未知次數的迴圈。單至少要先執行一次do,在判斷。如果while成立,繼續循環,反之,結束循環。

do {
 语句
 }while(条件表达式);

4、多次拷貝字串

測試所不能發現的一個錯誤是產生不可變(immutable)物件的多份拷貝。不可變物件是不可改變的,因此不需要拷貝它。最常用的不可變物件是String。

如果你必須改變一個String物件的內容,你應該使用StringBuffer。下面的程式碼會正常運作:

String s = new String ("Text here");

但是,這段程式碼效能差,而且沒有必要這麼複雜。你也可以用以下的方式來重寫上面的程式碼:

String temp = "Text here";
String s = new String (temp);

但這段程式碼包含額外的String,並非完全必要。更好的程式碼為:

String s = "Text here";

5、沒有複製(clone)回傳的物件

#封裝(encapsulation)是物件導向程式設計的重要概念。不幸的是,Java為不小心打破封裝提供了方便-Java允許傳回私有資料的參考(reference)。下面的程式碼揭示了這一點:

import java.awt.Dimension;
  /***Example class.The x and y values should never*be negative.*/
  public class Example{
  private Dimension d = new Dimension (0, 0);
  public Example (){ }
  /*** Set height and width. Both height and width must be nonnegative * or an exception is thrown.*/
  public synchronized void setValues (int height,int width) throws IllegalArgumentException{
  if (height <0 || width <0)
  throw new IllegalArgumentException();
  d.height = height;
  d.width = width;
  }
  public synchronized Dimension getValues(){
  // Ooops! Breaks encapsulation
  return d;
  }
  }

Example類別保證了它所儲存的height和width值永遠不是負數,試圖使用setValues()方法來設定負值會觸發例外。不幸的是,由於getValues()返回d的引用,而不是d的拷貝,你可以編寫如下的破壞性代碼:

  Example ex = new Example();
  Dimension d = ex.getValues();
  d.height = -5;
  d.width = -10;

現在,Example對象擁有負值了!如果getValues() 的調用者永遠也不設定傳回的Dimension物件的width 和height值,那麼僅憑測試就是不可能偵測到這類的錯誤。

不幸的是,隨著時間的推移,客戶程式碼可能會改變傳回的Dimension物件的值,這個時候,追尋錯誤的根源是件枯燥且費時的事情,尤其是在多執行緒環境中。

更好的方式是讓getValues()回傳拷貝:

  public synchronized Dimension getValues(){
  return new Dimension (d.x, d.y);
  }

6、拷貝錯誤的資料

有時候程式設計師知道必須回傳一個拷貝,但是卻不小心拷貝了錯誤的資料。由於僅僅做了部分的資料拷貝工作,下面的程式碼與程式設計師的意圖有偏差:

import java.awt.Dimension;
  /*** Example class. The height and width values should never * be
  negative. */
  public class Example{
  static final public int TOTAL_VALUES = 10;
  private Dimension[] d = new Dimension[TOTAL_VALUES];
  public Example (){ }
  /*** Set height and width. Both height and width must be nonnegative * or an exception will be thrown. */
  public synchronized void setValues (int index, int height, int width) throws IllegalArgumentException{
  if (height <0 || width <0)
  throw new IllegalArgumentException();
  if (d[index] == null)
  d[index] = new Dimension();
  d[index].height = height;
  d[index].width = width;
  }
  public synchronized Dimension[] getValues()
  throws CloneNotSupportedException{
  return (Dimension[])d.clone();
  }
  }

這兒的問題在於getValues()方法僅僅克隆了數組,而沒有克隆數組中包含的Dimension對象,因此,雖然呼叫者無法改變內部的陣列使其元素指向不同的Dimension對象,但是呼叫者卻可以改變內部的陣列元素(也就是Dimension物件)的內容。方法getValues()的較好版本為:

 public synchronized Dimension[] getValues() throws CloneNotSupportedException{
  Dimension[] copy = (Dimension[])d.clone();
  for (int i = 0; i
  // NOTE: Dimension isn’t cloneable.
  if (d != null)
  copy[i] = new Dimension (d[i].height, d[i].width);
  }
  return copy;
  }

在複製原子型態資料的多維數組的時候,也會犯下類似的錯誤。原子型別包括int,float等。簡單的克隆int型的一維數組是正確的,如下所示:

 public void store (int[] data) throws CloneNotSupportedException{
  this.data = (int[])data.clone();
  // OK
  }

拷貝int型的二維數組更複雜。 Java沒有int型的二維數組,因此一個int型的二維數組其實就是一個這樣的一維數組:它的型別為int[]。簡單的克隆int[][]型的陣列會犯下與上面範例中getValues()方法第一版本相同的錯誤,因此應該避免這麼做。下面的範例示範了在複製int型二維數組時錯誤的和正確的做法:

public void wrongStore (int[][] data) throws CloneNotSupportedException{
  this.data = (int[][])data.clone(); // Not OK!
  }
  public void rightStore (int[][] data){
  // OK!
  this.data = (int[][])data.clone();
  for (int i = 0; i
  if (data != null)
  this.data[i] = (int[])data[i].clone();
  }
  }

更多java知識請關注java基礎教程欄目。

以上是java幾種常見錯誤介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn