APCSA 考试中常见的 program error

APCSA速通】03 APCSA 考试中常见的 program error

Program Error

程序中的错误分为编译错误(语法错误)、运行时错误(异常)以及逻辑错误。

  • 语法错误syntax error / compile error,不能转换成计算机可以执行的代码

  • 异常runtime error, exception,部分程序可以运行,但是会报错导致程序崩溃

  • 逻辑错误logic error不报错,但是无法得出正确的结果

在二维数组出错之前,可以输出多少元素

Compile Error

compile error also calledsyntax error.

  • assign double to int variable

    inta=3.2;//compileerrorintb=(int)3.2;//rightdoublec=3;//assignmentconversion//cis3.0
  • assign length to array

  • arr.length = 10语法错误不能给数组的长度赋值

  • assign rows to 2darray or columns 2 2darray

    int[][]mat=newint[4][4];mat.length=10;//compileerror
  • overload

    • 两个方法的参数数量不同

    • 参数的数量相同,但是类型不一致

      classA{publicintadd(intx,inty){returnx+y;}//causecompileerrorpublicintadd(intm,intn){returnx+y;}}

      因为上面的两个方法参数类型都是两个整数,编译器认为是两个重复的方法,参数叫什么名字不重要。

    • 【考察方式】往往是问你那些方法(构造方法或者普通方法)添加到类中回导致compile-error或者那些方法添加到类中不会导致compile-error

  • call local variable or form parameter of other method

    classSome{publicvoida(inta){//acanonlybeusedinmethoda//scopeofaismethodlevel}publicvoidb(){intb=a;//cannotaccessafrombmethod}}
  • subclass can not find default constructor of super class

    classA{publicA(inta){}//compiledonot//generatedefaultconstructor//如果父类定义了有参数的构造方法//编译器不再生成没有参数的构造方法}classBextendsA{//cannotfinddefaultconstructorofsuperclass//子类默认隐式(implict)父类没有参数的构造方法}
  • 二维数组的遍历,对象当作索引

    Student[][]arr2d=newStudent[2][3];for(Studentk:arr2d){System.out.println(arr2d[k]);//errorSystem.out.println(k);//right}
  • 构造对象的时候访问了私有属性

    classPoint{privateintx,y;publicPoint(intx,inty){}}classCircle{privatePointp;privatedoubler;publicCircle(Pointp,doubler)}//=======Criclec=newCircle();c.p=newPoint(2,3);//compileerror//cannotacessprivateinstance//variable
classA{privateintnum1,num2;publicA(intn1,intn2){num1=n1;num2=n2;}publicintsum(){returnn1+n2;//error//n1n2的作用范围仅限于构造方法}}
  • 父类调用子类独有方法

    classAnimal{}classPersonextendsAnimal{publicvoidabstractThinking(){}}//=====callmethod====Animalp=newPerson();p.abstractThinking();//causecompileerror
  • 子类类型指向父类对象Person p = new Animal(); // error

  • 返回类型不兼容

    publicvoida(){returntrue;//error,returntypenotcompatable}

Runtime Error

runtime error also calledexception.

  • 3/0causeArithmetic exception

  • NullPointerException

    • 字符串不能调用方法

      String[]arr=newString[3];//default//valueofelementisnull//elementsnotinitializedarr[0].length();//causeNulPinterError
  • bounds error

    • ArrayIndexOutOfBoundarr[arr.length]

    • ArrayListIndexOutOfBoundlist.set(list.size(), 1)

    • StringIndexOutOfBoundstr.substring(str.length(), str.length()+1)

注意:

  • String substring(int start, int end)第二个参数可以是数组的长度

    str.substring(str.lenght());//emptystringstr.substring(1,1);//emptystring
  • ArrayListadd(int index)可以传递列表的值作为实际参数

    list.add(list.size(),"a");//rightlist.get(list.size());//right
  • 利用enhanced for loop修改ArrayListcauseConcurrency Exception

    ArrayList<String>list=newArrayList<>();list.add("a");for(Stringstr:list){list.add("s");//causeConcurrencyexceptionlist.remove(0);//causeConcurrencyexception}
  • recursion may casueStackOverflowException

    publicvoidcount(){count();}publicvoidmethod(intn){if(n>10){return0;}else{returnmethod(n-1);}}//====callmethod====method(0);//causeStackOverflowExceptionmethod(20);//0
  • 递归和二维数组

    int[][]arr2d={{1,2,3,4},{5,6,7,8}};publicintsum(int[]arr2d,intr,intc){if(r!=0||c!=0){returnarr2d[r][c]+sum(arr2d,r-1,c-1);}else{returnarr2d[r][c];}}//====callmethod====sum(arr2d,1,3);//causeboundserrorexceptionsum(arr2d,0,2);sum(arr2d,-1,1)//arr2d[-1][1]negtiveindexcause//ArrayIndexOutOfBoundexception

Logic Error

  • no usethiswhen form parameter same with form parameter

    //====wrongversion====classA{privateintnum;publicA(intnum){num=num;//cannotinitializethe//instanevaraible}}//====rightversion====classA{privateintnum;publicA(intnum){this.num=num;}}classA{privateintnum;publicA(intn){num=n;}}
  • for 循环查找存不存在循环体中出现 else

    /***serachvalueinarr*/publicbooleanhas(int[]arr,intvalue){for(inti=0;i<arr.length;i++){if(arr[i]==value){returntrue;}else//cannotusethiselse{returnfalse;//应该检查完所有元素//都不是value后返回false}}returnfalse;}//====callmethod====int[]arr={1,0,0,0};has(arr,0);//returnfalse,wrong
  • if-else-if 只要第一个条件成立其余的不看

    intscore=99;//shouldbea;Stringgrade="";if(score>=80){grade="b";//logicerrorifscore>=90}elseif(score>=90){grade="a";}
    • elseif 多选一,只要一个条件满足,其余的就不看了

  • if 顺序执行,后面的代码

    intscore=99;//shouldbea;Stringgrade="";if(score>=90){grade="a";}elseif(score>=80){grade="b";//}grade="A";//logicerrorifscore<90
  • ArrayList删除元素,部分元素被跳过

  • 递归导致的逻辑错误

    • 无限递归,查找元素是否存在 5

      publicbooleanfind(int[]arr,intlen){if(arr[len-1]==5){returntrue;}else{returnfind(arr,len-1);}}//====callmethod====int[]arr={1,2,3,4,5};find(arr);//returntrue;int[]arr1={0};//causeArrayIndexOutOfBounderrorfind(arr1);

      上面的方法,如果数组中,没有5,则一定会报错;有至少一个 5 则不会报错

    • 数组索引异常

  • 无限循环

    inti=0;while(i<arr.length){arr[i]=arr[i]*arr[i];//forgettoupdateloopvaraible//infiniteloop//needi+=1}
  • primitive can not modify

用增强 for 循环修改 primitive 数组中的值

int[]arr={1,2,3};for(intn:arr){n=n*2;}//不能把数组中的值变为原来两倍

因为增强 for 循环中循环变量中保存的是值的副本,整数、小数、boolean 传递的是值的副本。想要把数组的元素变为原来的两倍,应当使用 regular for loop

【竞赛报名/项目咨询请加微信:mollywei007】

微信扫一扫,分享到朋友圈

APCSA 考试中常见的 program error
上一篇

IGCSE 中文课程及难度怎么样?

下一篇

加拿大各省优势&优秀大学汇总

你也可能喜欢

  • 暂无相关文章!

关注热点

返回顶部