4: More Math and Variables

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Which of the following statements is false?

  1. A literal string is enclosed in double quotes.
  2. The + operator is used to join, or concatenate, two strings to make one longer string.
  3. To include a double quote inside a string, you must put an escape character in front of it.
  4. Strings are stored in either 4 or 8 bytes, depending on the precision you want.

Pair-Programming Exercise (end of class Monday)

4.1: More Math and Variables

Objectives

At the end of the lesson the student will be able to:

  • Rewrite assignment statements into shortcut alternatives
  • Diagnose problems with arithmetic precision and range and formulate solutions
  • Generate code to convert data from one type to another

4.1.1: Review of Arithmetic

  • Recall that Java uses the following operators for arithmetic
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • The dash (minus sign) is also used for negation
  • Arithmetic expressions are combinations of numbers, variables, constants and operators
  • double area = 0.0, radius = 4.5;
    final double PI = 3.14159;
    area = PI * radius * radius;
    
  • Operators have the same precedence as in algebra
    1. Parenthesis: ( )
    2. Method calls
    3. Unary operators: +, -
    4. Multiplication, division, modulus: *, /, %
    5. Addition, subtraction: +, -
  • Also recall that the results of integer division are truncated
  • You must use modulus operator (%) to get the remainder value
  • In addition, you use mathematical methods for more complex operations
  • System.out.println(Math.sqrt(3.0 * 3.0));

4.1.2: Magic Numbers

  • Imagine that you are a programmer hired to modify a payroll program
  • You come across the following section of code:
  • double pay;
    pay = hours * 7.5 + (hours / 40)
          * (hours - 40) * 7.5 * 0.5;
    
  • The numbers are important to the program, but what do they mean?
  • Numbers like these are called "magic numbers"
  • They are magic because the value or presence is unexplainable without more knowledge
    • Often, no one knows what they mean after 3 months, including the author
  • A programmer can often infer the meaning of numbers after reading the code carefully
  • Much better code is to use named constants rather than literal numbers
  • For example:
  • final double WAGE = 7.5;
    final double OVERTIME_ADDER = 0.5;
    final int HOURS_PER_WEEK = 40;
    double pay;
    pay = hours * WAGE + (hours / HOURS_PER_WEEK)
          * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
    
  • Now it is much easier to read and understand the code
    • And see any problems or limitations

Programming Style: Constant Variables and Magic Numbers

  • Since the meaning of literal ("magic") numbers is hard to remember, you should declare constants instead
  • final int FEET_PER_YARD = 3;
    final double PI = 3.14159;
    final double WAGE = 7.5;
    final double OVERTIME_ADDER = 0.5;
    final int HOURS_PER_WEEK = 40;
    
  • Note that the name is all uppercase letters with an underscore separator
  • This is a common coding convention that you must follow

4.1.3: Assignment Variations

  • Unlike math, you can have the same variable on both sides of an equals sign
  • int sum = 25;    // initialize sum to 25
    sum = sum + 10;  // add to sum
    
  • Note that the value of the variable is changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values

Abbreviated Assignment Expressions

  • Any statement of form: variable = variable <op> (expression);
  • May be written in an abbreviated form: variable <op>= expression;
  • <op> is one of: +, -, *, /, or %
  • For example:
  • sum = sum + 10;
    
  • Can be written as:
  • sum += 10;
    

Incrementing and Decrementing

  • Adding 1 to a number occurs frequently when programming
  • count = count + 1;
  • You can write this in an abbreviated form like:
  • count += 1;
  • Since it is so common, programmers wanted an even shorter form:
  • ++count;
    count++;
    
  • This is known as incrementing a variable
  • Similarly, you can decrement a variable
  • --count;
    count--;
    

4.1.4: Arithmetic Precision and Range

  • There are only so many possible numbers that can be stored in a variable
  • This limitation often leads to problems for the unwary

Integer Overflow

  • What happens when an integer is too big for its type?
  • System.out.print("Number too big: ");
    System.out.println(2147483647 + 1);
    System.out.print("Number too small: ");
    System.out.println(-2147483648 - 1);
    
  • Wraps around from the highest number to the lowest
  • Must be careful that your program will not go beyond the range of its data types

Floating-Point Precision and Range

  • Floating-point numbers are not exact representations of real numbers
  • Rounding errors occur in repeated calculations
  • Type double has about twice the precision of type float
  • However, even type double can have rounding errors
  • System.out.println(.8F + .1F);
    System.out.println(.7 + .1 + .1);
    
  • When floating point numbers get too large, they are set to infinity
  • System.out.println(1.7E308 + 1.7E308);
  • Similarly, when too small they are set to 0.0
  • System.out.println(4E-324 - 3E-324);

The Moral

  • Integer and floating-point data types work well most of the time
  • However, if you work with large positive or negative numbers, you must be sure you do not exceed the range of the data type
  • Also, floating-point numbers have limited precision
  • When math operations are performed repeatedly, they can become less precise
  • You must be careful of precision when using floating-point numbers

4.1.5: Type Casting

Cast: change the data type of the returned value of an expression

  • Recall that different data types are stored in different forms
  • Sometimes you need to change from one form to another
    • Example: arithmetic adding a double and an int value
    • Example: you want to truncate the remainder of a calculation
  • Java will automatically cast some data types to another
  • byte => short => int => long => float => double
                    /
             char =/
    
    • Also known as implicit casting
    • May not know how to convert some values
    • May not cast how the programmer wants
  • Programmers can also explicitly cast data types
  • Recall that casting is done automatically (implicitly) when a narrower-type is assigned to a broader-type
  • Explicit casting changes the data type for a single use of the variable
  • Precede the variable name with the new data type in parentheses:
  • (dataType) variableName
    
  • For example:
  • int n;
    double x = 2.5;
    n = (int) x;
    System.out.println("x = " + x);
    System.out.println("n = " + n);
    
  • Value of x is converted from type double to integer before assigning the value to n
  • Note that the data type is changed only for the single use of the returned value

Required Casting

  • Explicit casting is required to assign a broader type to a narrower type
  • ILLEGAL: Implicit casting to a narrower data type
  • int n;
    double x = 2.5;
    n = x; // illegal in java
    

    Illegal since x is double, n is an int, and double is a broader data type than int

  • Note that you can use an explicit cast even when an implicit one will be done automatically

Truncation When Casting Floating-Point to Integer type

  • Converting (casting) a floating-point to integer type does not round -- it truncates
  • Fractional part is lost (discarded, ignored, thrown away)
  • For example:
  • int n;
    double x = 3.99999;
    n = (int) x; // x truncated
    System.out.println("x = " + x);
    System.out.println("n = " + n);
    
  • Value of n is 3

Casting a char to an int

  • Casting a char value to int produces the ASCII/Unicode value
  • For example, what would the following display?
  • char answer = 'Y';
    System.out.println(answer);
    System.out.println((int) answer);
    
  • Answer:
  • >Y
    >89
    

4.1.6: Summary

  • Simple assignment statements have a variable, equals sign and an expression.
  • variable = expression;
  • The expression is computed before the assignment
  • Java has assignment variations of the form:
  • variable <op>= expression;
  • In addition, you can add to or subtract from variables the value one using increment (++) and decrement (--) operators
  • count++;
    count--;
    
  • Primitive variables have limitations in range and precision
  • If your program assigns values too high or too low, integers wrap around
  • Floating-point numbers usually have enough range
  • However, they often suffer from lack of precision
  • System.out.println(.8F + .1F);
    System.out.println(.7 + .1 + .1);
    
  • Type double has about twice the precision of type float
  • When floating point numbers get too large, they are set to inf
  • Similarly, when too small they are set to 0.0
  • Java will automatically cast variables of narrow types to wider types
  • byte => short => int => long => float => double
                    /
             char =/
    
  • You must use an explicit cast when assigning a broader type to a narrower type.
  • You can explicitly cast values of an expression to a different type.

Check Yourself

  1. How many ways can you add the integer 1 to a variable named index? List each way.
  2. What happens when you increase the value of an integer number beyond its range?
  3. How many digits that can be accurately stored in a float? double?
  4. What type of error occurs in the following expression?
  5. System.out.println(.7 + .1 + .1);
    
  6. Which is a valid typecast?
    1. a(int)
    2. int:a;
    3. (int)a;
    4. to(int, a);
  7. How do you truncate the decimal part of double variable?

Exercise 4.1

The following code does not display the correct value of degreesC.

1
2
3
4
5
6
7
8
9
10
import java.util.*;

public class FahrenheitConverter {
    public static void main(String[] args) {
        double degreesC, degreesF;
        degreesF = 212;
        degreesC = 5 / 9 * (degreesF - 32);
        System.out.println(degreesC);
    }
}

Specifications

  1. Save the code as FahrenheitConverter.java
  2. Use a cast to correct the code and obtain the correct output.
  3. Submit your program along with your other exercises for this lesson.

4.2: Making Selections

Objectives

At the end of the lesson the student will be able to:

  • Formulate relational expressions to produce boolean values
  • Generate selection statements

4.2.1: Flow of Control

  • The term flow of control refers to the order in which a computer executes instructions
  • All programs can be written with just three control-flow elements:
  1. Sequence - continue with the next instruction
    • All programs continue with the next instruction by default
    • To make the program do something else, you code either a selection or repetition (looping) statement
  2. Selection - a choice between at least two options
    1. Either execute some instruction based on a condition
    2. Or continue with the next instruction
    3. if
      if-else
      
  3. Repetition - a loop (repeat a block of code)
    At the end of the loop:
    • Either go back and repeat the block of code
    • Or continue with the next instruction after the block
    • for
      do-while
      while
      
  • We will first consider selection statements

4.2.2: The Value of a Relationship

  • To make a selection or repetition statement, you need to code a test condition
  • The computer uses the condition to decide whether or not to execute the statement
  • One way to code a test condition is to use a relational expression

Relational Expressions

  • In addition to arithmetical operations, all computers can compare numbers
  • Many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • Expressions that compare numbers are called conditions or relational expressions
  • Simple conditions have one relational operator comparing two values
  • relational expression

  • A condition always evaluates to either true or false
  • The relational operators are:
  • Math Name Java Example Result
    = Equal to == 5 == 10
    2 == 2
    false
    true
    Not equal to != 5 != 10
    2 != 2
    true
    false
    < Less than < 5 < 10
    5 < 5
    5 < 2
    true
    false
    false
    Less than or equal to <= 5 <= 10
    5 <= 5
    5 <= 2
    true
    true
    false
    > Greater than > 5 > 10
    5 > 5
    5 > 2
    false
    false
    true
    Greater than or equal to >= 5 >= 10
    5 >= 5
    5 >= 2
    false
    true
    true

  • You may use relational operators with any numerical data

4.2.3: Using if Statements

  • The simplest selection statement is an if statement
  • This statement executes a section of code only if a condition is true
  • If the test condition is false, the computer skips the code
  • if (condition) {
       // execute statements only if true
    }
    
  • For clarity:
    • Write the if on a different line than the executed block
    • Indent statements that are executed if the condition evaluates to true

For Example

  • What is new about the following code?
  • What is the test condition?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;

public class GuessingGame {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I'm thinking of a number "
            + " between 1 and 10.\nCan you guess it? ");
        int guess = input.nextInt();
        if (guess == 7) {
            System.out.println("*** Correct! ***");
        }
    }
}

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the block
  • Curly braces are not always required, but the best practice is to always include them

4.2.4: Using if-else Statements

  • Sometimes we want to choose between two actions
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • General syntax:
  • if (condition) { // evaluates to true
        // execute statements only if true
    } else {
        // execute statements only if false
    }
    
  • Note that there is no test condition for the else clause
  • The decision on which set of statements to use depends on only one condition
  • For clarity, write the if and else on different lines than the other statements
  • Also, indent the other statements

For Example

  • What do you notice that is different about the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.*;

public class GuessingGame2 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        int guess = 0;

        System.out.print("I'm thinking of a number "
            + " between 1 and 10.\nCan you guess it? ");
        guess = input.nextInt();
        if (guess == 7) {
            System.out.println("*** Correct! ***");
        } else {
            System.out.println("Sorry, that is wrong.");
        }
    }
}

Programming Style: Placement of Braces

  • Different practices for placing curly braces in a compound statement
  • Many programmers prefer placing curly braces on separate lines
  • However, Java standard is to place the opening brace on the same line as shown above
  • In practice, you should use the style dictated by your company's policy
    • Or your professor's instructions
  • For the acceptable styles for this course see: Curly Braces

4.2.5: Summary

  • Flow of control refers to the order in which a computer executes statements
  • There are only three types of flow of control
    1. Sequence: continue with the next instruction
    2. Selection: a choice between at least two options
    3. Repetition: repeat a block of code (loop)
  • To make a selection or repetition statement, you need to code a test condition
  • The computer uses the condition to decide whether or not to execute the statement
  • One way to code a test condition is to use a relation expression
  • Relational operators include:
  • ==  !=  <   <=  >   >=
  • Selection is a choice between at least two options
  • Selection statements include:
  • if
    if-else
    

Check Yourself

  1. What is meant by the term "flow of control"?
  2. What is the default flow-of-control" operation after a statement finishes executing?
  3. What two values can be returned from a relational expressions.
  4. What is the value of x after the following code segment?
  5. int x = 5;
    if (x > 3) {
        x = x - 2;
    } else {
        x = x + 2;
    }
    

Exercise 4.2

Take 10 minutes to complete the following:

  1. Start a text file named exercise4.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 4.2

Specifications

For the values:

int a = 5, b = 2, c = 4, d = 6;

Record the in your exercise4.txt file which of the following conditions are true and which are false.

  1. a > b
  2. a != b
  3. d % b == c % b
  4. a * c != d * b
  5. b % c * a != a * b

As a final part of this exercise, write a short program that asks the user for a test score. If the score is greater than or equal to 60 then print, "You passed!"; otherwise print, "Sorry, you failed"

Name this program TestScorer.java and submit it with the lesson 4 exercises. You may use the following code to get started.

import java.util.*;

public class TestScorer {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        System.out.println("Enter your test score: ");
        int score = input.nextInt();
        // Enter code here

    }
}

4.3: More About Selection

Objectives

At the end of the lesson the student will be able to:

  • Construct test conditions that evaluate to a boolean value
  • Use logical operators to assemble complex conditions
  • Avoid some common pitfalls when creating test conditions

4.3.1: Test Conditions and Boolean Values

  • All selection and loop statements have a test condition
  • This test condition controls the operation of the statement
  • You must construct test conditions so they always evaluate to a boolean value

Boolean Values

  • Boolean types have just one of two values: either true or false
  • boolean truth = true, lies = false;
    
  • Recall that an expression is part of a statement that returns a value
  • Thus, a boolean expression is some code that returns either true or false
  • For example:
  • true
    false
    2 < 5
    a == b
    
  • We use boolean expressions like these to control selection and looping statements

4.3.2: Comparing Characters

  • Character data can be evaluated using relational operators
  • For these comparisons, char values are automatically coerced to int values
  • Letters nearer to the start of the alphabet have lower numerical values
  • Thus a numerical comparison can decide the alphabetical order of characters
  • For example:
  • Expression Result
    'A' > 'C' false
    'D' <= 'Z' true
    'E' == 'F' false
    'G' >= 'M' false
    'B' != 'C' true

More Information

4.3.3: Nested if Statements

  • Note that you can include if statements within other if statements
  • Each inner if statement is evaluated only if the outer condition is met
  • This has the effect or requiring two conditions to evaluate to true before the statements of the inner if are executed

For Example

  • What do you notice that is different about the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;

public class TempGuide {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        System.out.print("Enter a temperature: ");
        double temp = input.nextDouble();

        if (temp > 65) {
            if (temp > 75) {
                System.out.println("That's too hot!");
            } else {
                System.out.println("That's just right.");
            }
        } else {
            System.out.println("That's cold!");
        }
    }
}

  • Nesting if statements inside of if statements can be confusing when too deep
  • Rule of thumb: no more than three deep

Nesting in the else Clause

  • You can also nest if statements in the else clause
  • This has the effect of testing another condition if the first one evaluates to false
  • For example, what do you notice that is different about the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.*;

public class TempGuide2 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        System.out.print("Enter a temperature: ");
        double temp = input.nextDouble();

        if (temp > 75) {        // first condition
            System.out.println("That's too hot!");
        } else if (temp > 65) { // second condition
            System.out.println("That's just right.");
        } else {                // default condition
            System.out.println("That's cold!");
        }
    }
}

  • Note the alignment of the nested statements
  • Instead of:
  • if (temp > 75) {
        System.out.println("That's too hot!");
    } else {
        if (temp > 65) {
            System.out.println("That's just right.");
        } else {
            System.out.println("That's cold!");
        }
    }
    
  • You format like this:
  • if (temp > 75) {
        System.out.println("That's too hot!");
    } else if (temp > 65) {
        System.out.println("That's just right.");
    } else {
        System.out.println("That's cold!");
    }
    
  • This structure clearly shows the operation of the code
  • Also, it prevents indentations cascading to the right

4.3.4: Testing Multiple Conditions

  • One reason to use nested if statements is for testing multiple conditions
  • However, a better way is to combine conditions using conditional operators
  • Conditional operators allow you to consider multiple cases and to change conditions

AND Operation

  • One such operator is "and", which is spelled && in Java
  • For example, the following is true if temp >= 65 and temp <= 75
  • (temp >= 65) && (temp <= 75)
  • When two boolean expressions are connected using && the whole expression is true only if both conditions are true
  • However, if either condition is false the whole expression is false

OR Operation

  • Also, you can combine two boolean expressions using the "or" operator, spelled || in Java
  • For example, the following is true if temp < 65 or temp > 75
  • (temp < 65) || (temp > 75)
  • When two boolean expressions are connected using || the whole expression is true if either condition is true
  • Only if both conditions are false is the entire expression false

NOT Operation

  • Additionally, you can negate any expression using ! operator
  • To use it, place the entire expression in parenthesis and place the ! operator in front
  • For example, to get a temp between 65 and 75, we can negate our previous example:
  • !((temp < 65) || (temp > 75))

Parenthesis

  • Remember that a boolean expression in an if statement must be enclosed in parenthesis
  • Thus, an if statement that uses an && operator with two comparisons looks like:
  • if ((temp >= 65) && (temp <= 75)) {
  • Also note that relational operators have a higher precedence than logical operators
  • Thus, you can remove the inner parenthesis without affecting the meaning
  • if (temp >= 65 && temp <= 75) {
  • However, if using parenthesis is clearer to you then use the extra parenthesis

For Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.*;

public class TempGuide3 {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        System.out.print("Enter a temperature: ");
        double temp = input.nextDouble();

        if (temp >= 65 && temp <= 75) {
            System.out.println("That's just right.");
        } else {
            System.out.println("That's uncomfortable!");
        }
    }
}

4.3.5: Summary

  • All selection and repetition statements have a test condition
  • This test condition controls the operation of the statement
  • You must construct test conditions so they always evaluate to a boolean value
  • Boolean types have just one of two values: either true or false
  • A boolean expression is any expression that returns either true or false
  • You can compare letters as well as numbers since letters are stored as numbers
    • Used to alphabetize letters and words in a computer program
  • Nested if statements are legal but often confusing
    • Best to avoid nesting if statements in the if clause
  • In contrast, nesting if statements in the else clause is fine
  • When you need to compare several conditions, you use logical operators
  • !   &&  ||
  • For example:
  • (temp >= 65) && (temp <= 75)
    (temp < 65) || (temp > 75)
    !((temp < 65) || (temp > 75))
    

Check Yourself

  1. What two values can a boolean variable contain?
  2. Why can you compare character data using a relational expression?
  3. What is the effect of having an if statement nested in an if statement?
  4. What is the effect of having an if statement nested in an else statement?
  5. When does an AND (&&) of two or more conditions evaluate to true?
  6. When does an OR (||) of two or more conditions evaluate to false?
  7. What is the effect of the NOT (!) operator?

Exercise 4.3

Specifications

A student's letter grade is calculated according to the following table:

Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F

  1. Save the following code as GradeConverter.java
  2. Change the code to:
    1. Get a score from the users as an double number between 0 and 100
    2. Convert the score to a letter grade
    3. Display the letter grade
  3. Submit your program along with your other exercises for this lesson.
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.*;

public class GradeConverter {
    public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);
        System.out.print("Enter a score ");
        double score = input.nextDouble();

        // Insert statements here

    }
}

4.4: Testing and Debugging

Objectives

At the end of the lesson the student will be able to:

  • Describe the three kinds of programming errors
  • Find the syntax errors in your programs

4.4.1: Kinds of Programming Errors

  • There are three types of programming errors
    • Syntax Errors
    • Run-time Errors
    • Logic Errors

Syntax Errors

  • Violation of the "grammar" rules of the programming language
  • For instance: forgetting a semicolon
  • Syntax errors are discovered by the compiler
  • You program will not compile if you have a syntax error

Errors Versus Warnings

  • If you violate a syntax rule, the compiler gives you an error message
  • Sometime the compiler will give you are warning message instead
  • This indicates that your code is technically correct
  • However, your code is unusual enough that it is probably a mistake
  • Thus, you lose points for warning messages in your programming assignments

Run-time Errors

  • Error conditions are sometimes detected by the computer at run-time
  • For example: trying to divide by zero
  • You program will usually end when it detects these errors
  • How do you make sure your program does not have this type of error?

Logic Errors

  • Errors in the program's algorithm
  • For example: subtracting rather than adding in an arithmetic formula
  • Computer does not recognize these types of errors
  • Makes them the most difficult to diagnose
  • How do you make sure your program does not have this type of error?

4.4.2: Anatomy of an Error Message

  • To debug your programs you have to read the error messages
  • As you read them you need to extract the important information
  • For example, this error message tells you several important things:
  • Fiddle.java:7: unclosed string literal
    System.out.println("Hello, world!);
                       ^
    
  1. The name of the program
  2. Fiddle.java:7: unclosed string literal
  3. The line number of the error
  4. Fiddle.java:7: unclosed string literal
  5. The error description
  6. Fiddle.java:7: unclosed string literal
  7. The character position where the compiler became confused
  8. System.out.println("Hello, world!);
                       ^
    
  • The most immediately useful information is the line number

4.4.3: How To Debug Syntax Errors

Repeat the following process until all the compiler errors are gone.

  1. Find the first error only.
  2. You should look at the first error and ignore the rest. Often the first error causes all the rest of the errors. Reading any error beyond the first is often a waste of time.

  3. Analyze the first error.
  4. Find the line reported by the first error. This is the line where the compiler first got confused. Look at this line in your code and try to spot the problem. The error message may provide clues as to the problem. If you cannot see a problem on that line, look for a problems on lines just before the reported line.

  5. If you cannot find the error in your code, then look at the causes of common errors in the next section.
  6. Most times, you will spot the error. If you do not, then compare the first error message with those listed below. If you still cannot find your error, show it to the instructor. He will help you find and correct the problem. You can either bring it to him in person or email him.

  7. After correcting the first error, try to recompile your program.

4.4.4: Some Error Messages and Their Common Causes

Instructions

  • If you cannot see an error in your code on or before the reported line number, then read the error message
  • Compare the error description to the list below

unclosed comment

This error is usually caused by a missing end of a comment (*/). For example, the following code:

/**
 * Hello.java
 * Purpose: Prints a message to the screen.
 *
 * @author Ed Parrish
 * @version 1.0 8/30/05

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

generates the following error:

Hello.java:1: unclosed comment
/**
^

To fix it, add the closing comment: */

']' expected

This error is usually caused by a missing square bracket (]). For example, the following code:

public class HelloWorld {
     public static void main(String[ args) {
        System.out.println("Hello, world!");
    }
}

generates the following error:

HelloWorld.java:2: ']' expected
     public static void main(String[ args) {
                                     ^

To fix it, add the closing square bracket: ]

';' expected

This error is usually caused by a semicolon (;). For example, the following code:

public class HelloWorld {
     public static void main(String[] args) {
        System.out.println("Hello, world!")
    }
}

generates the following error:

HelloWorld.java:4: ';' expected
    }
    ^

Note that the line reported for the error is off by one number. To fix the problem, add the missing semicolon: ;

unclosed string literal

This error is usually caused by a double quote ("). For example, the following code:

public class HelloWorld {
     public static void main(String[] args) {
        System.out.println("Hello, world!);
    }
}

generates the following error:

HelloWorld.java:3: unclosed string literal
        System.out.println("Hello, world!);
                           ^

To fix the problem, add the missing double quote: "

'class' or 'interface' expected

This is a general-purpose syntax error and is often caused by:

  • An extra closing curly bracket (})
  • A space between the slashes of a single-line comment

For example, the extra curly bracket in this code:

public class HelloWorld {
     public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}}

generates the following error:

HelloWorld.java:5: 'class' or 'interface' expected
}}
 ^

To fix the problem, remove the extra curly bracket: }

4.4.5: Summary

  • There are three kinds of programming errors
    • Syntax errors
    • Run-time Errors
    • Logic Errors
  • Sometimes the compiler will issue a warning if your code is unusual but still correct
  • You should treat this warning as an error because it probably is a logic error
  • Syntax errors are the easiest errors to find and correct
  • I provide some instructions for finding and correcting these errors
  • This information is summarized in How To Debug Compiler Errors

Check Yourself

  1. What are the three kinds of programming errors?
  2. What is the most useful information you can extract from an error message?
  3. What is the process for debugging syntax errors?
  4. What is the purpose of testing code that compiles without error?

Exercise 4.4

  1. Label this exercise: Exercise 4.4
  2. Submit all exercises for today's lesson in one file unless instructed otherwise
  3. Complete the following and list the error messages you found and what you did to correct them in your exercise4.txt file.

Specifications

The following program was written by a person in a hurry. During the entry process a large number of errors were made. You need to find and correct the errors reported by the compiler by following the process described in section 4.4.3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Scanner;

/**
 * Erroneous.java
 * A very erroneous program.
 *
 * @author B. A. Ware
 * @version 1.0 9/15/05

public class Erroneous {
    public static void main(String[ args) {
        Scanner input  = now Scanner(System.in);
        System.out.print("Enter a message: ");
        String message = input.nextLine();
        System.out.println("Your message:  + message);
    } // end of main method
}} / / end of Erroneous class

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: December 25 2005 @20:03:35