大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 學習攻略 16個java常見錯誤以及避免方法

16個java常見錯誤以及避免方法

更新時間:2019-09-17 15:42:51 來源:動力節點 瀏覽6615次

  

今天動力節點java培訓機構小編為大家介紹“16個java常見錯誤以及避免方法”,希望通過此文能夠幫助到各位java程序員,下面就隨小編一起來了解一下16個java常見錯誤以及避免方法。


     u=413209375,3586319870&fm=11&gp=0.jpg


  1、“… Expected”


  當代碼中缺少某些東西時,會產生這個錯誤。通常這是因為缺少一個分號或右括號。


  Java代碼:


private static double volume(String solidom, double alturam, double areaBasem, double raiom) {  

double vol;  

    if (solidom.equalsIgnoreCase("esfera"){  

        vol=(4.0/3)*Math.pi*Math.pow(raiom,3);  

    }  

    else {  

        if (solidom.equalsIgnoreCase("cilindro") {  

            vol=Math.pi*Math.pow(raiom,2)*alturam;  

        }  

        else {  

            vol=(1.0/3)*Math.pi*Math.pow(raiom,2)*alturam;  

        }  

    }  

    return vol;  

}  


  通常,這種錯誤消息不會指出產生問題的確切位置。要找出問題所在,需要:


  (1)確保所有的左括號都有相應的右括號。


  (2)查看錯誤所指示的那一行前面的代碼。這個錯誤通常是在后面的代碼中才會被編譯器發現。


  (3)有的時候,有些字符(例如左括號)不應該位于Java代碼的第一個。



  2、“Unclosed String Literal”


  當字符串結尾缺少引號時,會產生“unclosed string literal”錯誤消息,并且該消息就顯示在出錯的那一行上。


  Java代碼:


public abstract class NFLPlayersReference {  

   private static Runningback[] nflplayersreference;  

   private static Quarterback[] players;  

   private static WideReceiver[] nflplayers;  

   public static void main(String args[]){  

   Runningback r = new Runningback("Thomlinsion");  

   Quarterback q = new Quarterback("Tom Brady");  

   WideReceiver w = new WideReceiver("Steve Smith");  

   NFLPlayersReference[] NFLPlayersReference;  

       Run();// {  

       NFLPlayersReference = new NFLPlayersReference [3];  

       nflplayersreference[0] = r;  

       players[1] = q;  

       nflplayers[2] = w;  

           for ( int i = 0; i < nflplayersreference.length; i++ ) {  

           System.out.println("My name is " + " nflplayersreference[i].getName());  

           nflplayersreference[i].run();  

           nflplayersreference[i].run();  

           nflplayersreference[i].run();  

           System.out.println("NFL offensive threats have great running abilities!");  

       }  

   }  

   private static void Run() {  

       System.out.println("Not yet implemented");  

   }       


  通常,這種錯誤在以下這些情況下會產生:


  (1)字符串不是以引號結尾。這很容易修改,用指定的引號來結束字符串即可。


  (2)字符串超出一行。長字符串可以分成多個短串,并用加號(“+”)連接。


  (3)作為字符串一部分的引號沒有使用反斜杠(“\”)來進行轉義。



  3、“Public Class XXX Should Be in File”


  當XXX類和Java程序文件名不匹配時,就會產生“public class XXX should be in file”錯誤消息。 只有當類名和Java文件名相同時,才能編譯代碼。


  Java代碼:


package javaapplication3;    

  public class Robot {    

        int xlocation;    

        int ylocation;    

        String name;    

        static int ccount = 0;    

        public Robot(int xxlocation, int yylocation, String nname) {    

            xlocation = xxlocation;    

            ylocation = yylocation;    

            name = nname;    

            ccount++;           

        }   

  }  

  public class JavaApplication1 {   

    public static void main(String[] args) {    

        robot firstRobot = new Robot(34,51,"yossi");    

        System.out.println("numebr of robots is now " + Robot.ccount);    

    }  

  }  


要解決這個問題,可以:


  (1)把類和文件命名為相同的名字。


  (2)確保兩個名稱始終保持一致。



  4、“Incompatible Types”


  “Incompatible Types”是賦值語句嘗試對變量與表達式進行類型匹配時發生的邏輯錯誤。通常,將字符串賦值給一個整數時會產生這個錯誤,反之亦然。這不是一個Java語法錯誤。


  Java代碼:


test.java:78: error: incompatible types  

return stringBuilder.toString();  

                             ^  

required: int  

found:    String  

1 error  


  當編譯器拋出“incompatible types”消息時,確實不太容易解決這個問題:


  (1)使用類型轉換函數。


  (2)開發人員可能需要修改代碼原有的功能。



  5. “Invalid Method Declaration; Return Type Required”


  這個錯誤消息的意思是,在方法聲明中未顯示地聲明方法的返回類型。


  Java代碼:


public class Circle  

{  

    private double radius;  

    public CircleR(double r)  

    {  

        radius = r;  

    }  

    public diameter()  

    {  

       double d = radius * 2;  

       return d;  

    }  

}  


  有這幾種情況會觸發“invalid method declaration; return type required”錯誤:


  (1)忘記聲明類型。


  (2)如果方法沒有返回值,那么需要在方法聲明中指定“void”作為返回類型。


  (3)構造函數不需要聲明類型。但是,如果構造函數名稱中存在錯誤,那么編譯器會把構造函數看成是沒有指定類型的方法。



  6、“Method in Class Cannot Be Applied to Given Types”


  這個錯誤消息比較有用,它的意思是某個方法調用了錯誤的參數。


  Java代碼:


RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;  

generateNumbers();  

  

required: int[]  

  

found:generateNumbers();  

  

reason: actual and formal argument lists differ in length  


  在調用方法時,應傳入在其聲明時定義的那些參數。請檢查方法聲明和方法的調用,以確保它們是匹配的。



  7、“Missing Return Statement”


  當一個方法缺少return語句時,會觸發“Missing Return Statement”錯誤消息。有返回值(非void類型)的方法必須要有一條返回某個值的語句,以便在方法之外調用該值。


  Java代碼:


public String[] OpenFile() throws IOException {  

    Map<String, Double> map = new HashMap();  

    FileReader fr = new FileReader("money.txt");  

    BufferedReader br = new BufferedReader(fr);  

    try{  

        while (br.ready()){  

            String str = br.readLine();  

            String[] list = str.split(" ");  

            System.out.println(list);                 

        }  

    }   catch (IOException e){  

        System.err.println("Error - IOException!");  

    }  

}  


  編譯器拋出“missing return statement”消息有這幾個原因:


  (1)返回語句被錯誤地省略了。


  (2)該方法沒有返回任何值,但是在方法聲明中未聲明類型為void。



  8、“Reached End of File While Parsing”


  這個錯誤消息通常在程序缺少右大括號(“}”)時觸發。有時,在代碼的末尾增加右大括號可以快速地修復此錯誤。


  Java代碼:


public class mod_MyMod extends BaseMod  

public String Version()  

{  

     return "1.2_02";  

}  

public void AddRecipes(CraftingManager recipes)  

{  

   recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {  

      "#", Character.valueOf('#'), Block.dirt  

   });  

}  


  上述代碼會產生以下這個錯誤:


  (1)Java代碼


  java:11: reached end of file while parsing }


  編碼工具和適當的代碼縮進可以更容易地找到這些不匹配的大括號。


  

  9、“Unreachable Statement”


  當一條語句出現在一個它不可能被執行的地方時,會觸發“Unreachable statement”錯誤。通常,是在一個break或return語句之后。


  Java代碼:


for(;;){  

   break;  

   ... // unreachable statement  

}  

int i=1;  

if(i==1)  

  ...  

else  

  ... // dead code  


  通常,簡單地移動return語句即可修復此錯誤。



  10、“Illegal Start of an Expression”


  出現“Illegal Start of an Expression”錯誤的原因有很多。它已經成為不太有用的錯誤消息之一。一些開發者認為這是由壞的代碼味道造成的。


  通常,創建一個表達式是為了生成一個新值或給其他變量賦值。編譯器期望找到一個表達式,但是因為語法不符合預期而找不到表達式。在下面這些代碼中可以找到這種錯誤。


Java代碼 :


} // 把它添加到這里  

       public void newShape(String shape) {  

        switch (shape) {  

            case "Line":  

                Shape line = new Line(startX, startY, endX, endY);  

            shapes.add(line);  

            break;  

                case "Oval":  

            Shape oval = new Oval(startX, startY, endX, endY);  

            shapes.add(oval);  

            break;  

            case "Rectangle":  

            Shape rectangle = new Rectangle(startX, startY, endX, endY);  

            shapes.add(rectangle);  

            break;  

            default:  

            System.out.println("ERROR. Check logic.");  

        }  

        }  

    } // 從這里刪掉它  

    }  



  11、“Variable Might Not Have Been Initialized”


  在方法中聲明的局部變量如果沒有初始化,就會發生這種錯誤。如果在if語句中包含沒有初始值的變量時,就會發生這種錯誤。


  Java代碼:


int x;  

if (condition) {  

    x = 5;  

}  

System.out.println(x); // x可能尚未初始化  



  12. “Operator … Cannot be Applied to ”


  當操作符作用于未在其定義范圍內的類型時,會出現此問題。


  Java代碼:


  operator < cannot be applied to java.lang.Object,java.lang.Object


  當Java代碼嘗試在計算(減法、乘法、大小比較等)中使用字符串類型時,經常會觸發這種錯誤。要修復這個問題,需要將字符串轉換為整數或浮點數。



  13、“Missing Return Value”


  當返回語句包含不正確的類型時,你會收到“Missing Return Value”消息。例如,查看以下代碼:


  Java代碼:


public class SavingsAcc2 {  

    private double balance;  

    private double interest;  

    public SavingsAcc2() {  

        balance = 0.0;  

        interest = 6.17;  

    }  

    public SavingsAcc2(double initBalance, double interested) {  

        balance = initBalance;  

        interest = interested;  

    }  

    public SavingsAcc2 deposit(double amount) {  

        balance = balance + amount;  

        return;  

    }  

    public SavingsAcc2 withdraw(double amount) {  

        balance = balance - amount;  

        return;  

    }  

    public SavingsAcc2 addInterest(double interest) {  

        balance = balance * (interest / 100) + balance;  

        return;  

    }  

    public double getBalance() {  

        return balance;  

    }  

}  


  返回以下錯誤:


  Java代碼:

  

SavingsAcc2.java:29: missing return value   

return;   

^   

SavingsAcc2.java:35: missing return value   

return;   

^   

SavingsAcc2.java:41: missing return value   

return;   

^   

3 errors  


  通常,這個錯誤的出現是因為有某個返回語句沒有返回任何東西。



  14、 “Cannot Return a Value From Method Whose Result Type Is Void”


  當一個void方法嘗試返回任何值時,會發生此Java錯誤,例如在以下代碼中:


  Java代碼:


public static void move()  

{  

    System.out.println("What do you want to do?");  

    Scanner scan = new Scanner(System.in);  

    int userMove = scan.nextInt();  

    return userMove;  

}  

public static void usersMove(String playerName, int gesture)  

{  

    int userMove = move();  

    if (userMove == -1)  

    {  

        break;  

    }  


  通常,更改方法的返回類型與返回語句中的類型一致,可以解決這個問題。例如,下面的void可以改為int:


  Java代碼:


public static int move()  

{  

    System.out.println("What do you want to do?");  

    Scanner scan = new Scanner(System.in);  

    int userMove = scan.nextInt();  

    return userMove;  

}  



  15、 “Non-Static Variable … Cannot Be Referenced From a Static Context”


  當編譯器嘗試在靜態方法中訪問非靜態變量時,會發生此錯誤:


  Java代碼:


public class StaticTest {  

    private int count=0;  

    public static void main(String args[]) throws IOException {  

        count++; //compiler error: non-static variable count cannot be referenced from a static context  

    }  

}  


  要解決“Non-Static Variable … Cannot Be Referenced From a Static Context”這個錯誤,可以做兩件事情:


  (1)可以將變量聲明為靜態。


  (2)可以在靜態方法中創建非靜態對象的實例。



  16、 “Non-Static Method … Cannot Be Referenced From a Static Context”


  當Java代碼嘗試在靜態類中調用非靜態方法時,會發生此問題。例如,以下代碼:


  Java代碼:


class Sample  

{  

   private int age;  

   public void setAge(int a)  

   {  

      age=a;  

   }  

   public int getAge()  

   {  

      return age;  

   }  

   public static void main(String args[])  

   {  

       System.out.println("Age is:"+ getAge());  

   }  

}  


  會觸發這個錯誤:


  Java代碼:


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

Cannot make a static reference to the non-static method getAge() from the type Sample  


  要在靜態方法中調用非靜態方法,需要是聲明一個要調用的非靜態方法的類的實例。


以上就是動力節點java培訓機構小編介紹的“16個java常見錯誤以及避免方法”的內容,希望對大家有幫助,更多java最新資訊請繼續關注動力節點java培訓機構官網,每天會有精彩內容分享與你。


相關免費視頻教程推薦


java初學者視頻教程下載——常見錯誤:http://www.dabaquan.cn/xiazai/2607.html


提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 99re国产精品视频首页 | 福利视频在线播放 | 婷婷色在线播放 | 国内精品一区视频在线播放 | 亚洲综合狠狠99婷婷 | 四虎. com 官网| 国产精品久久久久久久久免费hd | 久久夜色撩人精品国产 | 日日摸夜夜欧美一区二区 | 国产亚洲欧美日韩在线看片 | 欧美精品中文字幕手机免费视频 | 四虎永久免费观看 | 国产一区亚洲 | 真实偷清晰对白在线视频 | 五月天激情婷婷 | 人人干天天干 | 久久九色| 亚洲精品一区二区三区婷婷月 | 一级毛片免费播放 | 69色视频日韩在线视频 | 欧美亚洲另类色国产综合 | 四虎国产在线观看 | 四虎在线最新地址公告 | 国产在线精品观看 | 久久精品全国免费观看国产 | 亚洲免费a | 国产成人亚洲欧美三区综合 | 久草在线免费资源 | 欧美人与鲁交大毛片免费 | 久久成人免费大片 | a一级毛片免费播放 | 国产免费一级精品视频 | 日韩精品中文字幕一区三区 | 国产午夜精品久久久久九九 | 幻女bbwxxxxyounu | 国产目拍亚洲精品一区麻豆 | 国产精品第1页在线播放 | 成人影院www在线观看 | 久久久精品中文字幕 | 一级毛片免费视频网站 | 福利视频在线免费观看 |