Java - Lecture 6
Java - Lecture 6
2
Recognizing Error Types
• Identifying syntax errors
• Identifying runtime errors
• Identifying logical errors
3
Identifying Syntax Errors
• Misspelled class, variable, or method names
• Misspelled keywords
• Missing semicolons
• Missing return type for methods
• Out of place or mismatched parentheses and brackets
• Undeclared or uninitialized variables
• Incorrect format of loops, methods, or other structures
4
Identifying Syntax Errors
public class errors {
5
Identifying Syntax Errors
public class Errors {
7
Identifying Logical Errors
public class Errors {
for (int i = age; i <= 65; i++){ public static BigDecimal recalculate(BigDecimal
retirementFund = recalculate(retirementFund,new fundAmount, BigDecimal rate){
BigDecimal("0.10")); // use BigDecimal methods for arithmetic
} // operations
return fundAmount.multiply(rate.add(new
BigDecimal monthlyPension =
retirementFund.divide(yearsInRetirement.multiply(new BigDecimal("1.00")));
BigDecimal("12.00")),2, BigDecimal.ROUND_HALF_UP); }
System.out.println(name + " will have $" + monthlyPension+ " per
}
month for retirement.");
} Output:
… David Johnson will have $1288.03 per month
for retirement.
11
Identifying Logical Errors
import java.math.BigDecimal; System.out.println(name + " will have $" +
import java.math.RoundingMode; monthlyPension+ " per month for retirement.");
public class Errors { }
…
public static void main(String[] args) {
int age = 30;
public static BigDecimal recalculate(BigDecimal
BigDecimal retirementFund = new BigDecimal("10000.00"); fundAmount, BigDecimal rate){
// use BigDecimal methods for arithmetic
// set the scale to 2 decimal points // operations
// and the rounding to round up when the next digit is >= 5 return fundAmount.multiply(rate.add(new
retirementFund = retirementFund.setScale(2, BigDecimal("1.00")));
RoundingMode.HALF_UP); }
}
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = "David Johnson";
13
Exceptions
public class ExceptionExamples {
class Person{
String name;
int age;
}
14
Exceptions
public class ExceptionExamples {
class Person{
String name;
int age;
} Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable employee may not have been initialized.
15
Exceptions
public class ExceptionExamples {
class Person{
String name;
int age;
} Output:
null is 0 years old.
16
Exceptions
public class ExceptionExamples { class Person{
public static void main(String[] args) String name;
{ int age;
Person employee = new Person(); JobType job;
printPerson(employee); Person (){
} }
public static void printPerson(Person }
myPerson){ class JobType{
System.out.println(myPerson.name + " String jobName;
is " + myPerson.age + " years old and int salaryBand;
works as a " + myPerson.job.jobName);
JobType (){
}
}
}
}
…
17
Exceptions
public class ExceptionExamples { class Person{
public static void main(String[] args) String name;
{ int age;
Person employee = new Person(); JobType job;
printPerson(employee); Person (){
} }
public static void printPerson(Person }
myPerson){ class JobType{
System.out.println(myPerson.name + " String JobName;
is " + myPerson.age + " years old and int salaryBand;
works as a " + myPerson.job.JobName);
JobType (){
}
}
}
}
…
Output:
Exception in thread "main" java.lang.NullPointerException 18
Exceptions
public class ExceptionExamples { class Person{
String name;
int age;
public static void main(String[] args) {
JobType job;
JobType manager = new JobType("Manager", 6);
Person employee = new Person("Bob Little", 47,
Person (String name, int age, JobType job){
manager);
this.name = name;
printPerson(employee);
this.age = age;
}
this.job = job;
}
public static void printPerson(Person myPerson){ }
System.out.println(myPerson.name + " is " + class JobType{
myPerson.age + String JobName;
" years old and works as a " + int salaryBand;
myPerson.job.JobName);
} JobType (String name, int band){
} JobName = name;
… salaryBand = band;
Output: }}
Bob Little is 47 years old and works as a Manager
19
Exceptions
public class IndexExceptionExample {
20
Exceptions
public class IndexExceptionExample {
} Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
21
Exceptions
public class IndexExceptionExample {
}
23
Exceptions
import java.util.ArrayList;
25
Exceptions
public class EndlessMethodCall {
try{
int ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae) {
System.out.println("Denominator should not be 0!");
}
}
}
Output:
Denominator should not be 0!
28
Catching Exceptions
public class Error {
try{
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
}}
Output:
Infinity 29
Catching Exceptions
public class Error {
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0!");}
}
} Output:
Denominator should not be 0!
30
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=2;
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
finally{
System.out.println("Finally was reached!");} Output:
}} 5.0
Finally was reached!
31
Catching Exceptions
public class Error {
public static void main(String[] args) {
double numerator=10;
double denominator=0;
try{
if (denominator == 0) {throw new ArithmeticException();};
double ratio= numerator/denominator;
System.out.println(ratio);
} catch (ArithmeticException ae){
System.out.println("Denominator should not be 0.");}
finally{
System.out.println("Finally was reached!");}
}} Output:
Denominator should not be 0.
Finally was reached!
32
Catching exceptions
import java.text.DecimalFormat; System.out.println("Please provide correct
import java.util.InputMismatchException; input!");
import java.util.Scanner; } finally {
public class Error { scan.close();
static Scanner scan = new Scanner(System.in); }}}
public static void main(String[] args) {
try {
System.out.print("Enter the loan amount: ");
double principle = scan.nextDouble();
System.out.print("Enter the interest rate: ");
double rate = scan.nextDouble(); Input:
System.out.print("Enter the loan term (in years): "); Enter the loan amount: Bart
double years = scan.nextInt(); Output:
double interest = principle*rate*years;
double total = principle + interest;
Please provide correct input!
double payment = total/years/12;
DecimalFormat df = new DecimalFormat ("0.##");
System.out.println("Monthly payment: $“ + df.format(payment));
} catch (InputMismatchException exc){
…
33
Catching exceptions
import java.text.DecimalFormat;
import java.util.Scanner;
public class Error {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)){
System.out.print("Enter the loan amount: ");
double principle = scan.nextDouble();
System.out.print("Enter the interest rate: ");
double rate = scan.nextDouble();
System.out.print("Enter the loan term (in years): ");
double years = scan.nextInt();
double interest = principle*rate*years;
double total = principle + interest;
double payment = total/years/12;
DecimalFormat df = new DecimalFormat ("0.##");
System.out.println("Monthly payment: $" + df.format(payment));
} catch (Exception exc){
System.out.println(exc);
}}}
34
Catching exceptions
import java.text.DecimalFormat; public static double[] scanValues() throws
import java.util.InputMismatchException; InputMismatchException {
import java.util.Scanner; double[] values = new double[3];
Scanner scan = new Scanner(System.in);
public class Error {
try {
public static void main(String[] args) {
System.out.print("Enter loan amount: ");
try {
values[0] = scan.nextDouble();
double[] userValues = scanValues();
double payment = System.out.print("Enter interest rate: ");
(userValues[0]+userValues[0]*userValues[1]*userValues[2])/userV values[1] = scan.nextDouble();
alues[2]/12; System.out.print("Enter loan term: ");
DecimalFormat df = new DecimalFormat("0.##"); values[2] = scan.nextInt();
System.out.println("Monthly payment: $" + df.format(payment)); } finally {
} catch (InputMismatchException ime) {
scan.close();
System.out.println("You must enter double values! ");
}
System.exit(0);
return values;
} catch (ArithmeticException ae) {
System.out.println("Arithmetic error! ");
}}
System.exit(0);
} catch (IndexOutOfBoundsException ioob) {
System.out.println("Three doubles are required! ");
Input:
System.exit(0); Enter the loan amount: Bart
}} Output:
You must enter double values!
35
Conclusions
• Recognizing error types
• Exceptions
• Debugging Your Applications
• Testing Your Applications
36