首页 课程 师资 教程 报名

16个java常见错误以及避免方法

  • 2019-09-17 15:42:51
  • 5130次 动力节点

  

今天动力节点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.bjpowernode.com/xiazai/2607.html


选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交