CSE 2001Y Lab Sheet 2 - Problems

Embed Size (px)

Citation preview

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    1/6

    1

    UNIVERSITY OF MAURITIUS

    Faculty of Engineering

    Department of Computer Science & Engineering

    Module: Software Engineering (CSE 2001Y)Lab-sheet 2: Week 2, Semester 1, 2010/2011

    1. Analyze the following program and figure out its output.public class MoreSausages {

    public static void main(String[] args) {

    int sausages = 27;

    sausages++;

    System.out.println(sausages);System.out.println(sausages++);System.out.println(sausages--);

    }

    }

    NOTE THE FOLLOWING WELL:

    The increment operator ++ can be put after a variable (a++). When this isdone, it is a postfix operator. Same applies for the decrement operator --(which gives a--).

    When the increment operator ++ is put before a variable (++a), it is a

    prefix operator. Same applies for the decrement operator -- (which gives--a).

    A postfix expression (a++ or a--) produces a pure value that is the valueof the variable before it is incremented or decremented.

    A prefix expression (++a or --a) produces a pure value that is the valueof the variable after it has been incremented or decremented.

    In summary:

    postfix expression a++ or a--++a means increment the value before using it.Same for a--

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    2/6

    2

    prefix expression ++a or --aa++ means increment the value after using it.Same for a

    Example 1:

    //Increment.java// Prefix increment and postfix increment operators.

    public class Increment{public static void main( String args[] )

    {int c;

    // demonstrate postfix increment operator

    c = 5; // assign 5 to cSystem.out.println( c ); // prints 5System.out.println( c++ ); // prints 5 then postincrementsSystem.out.println( c ); // prints 6

    System.out.println(); // skip a line

    // demonstrate prefix increment operatorc = 5; // assign 5 to cSystem.out.println( c ); // prints 5

    System.out.println( ++c ); // preincrements then prints 6

    System.out.println( c ); // prints 6

    } // end main

    } // end class Increment

    Example 2:int i = 3, j = 3; //short for int i = 3; int j = 4;//System.out.println( "i++ produces " + i++);

    System.out.println( "++j produces " + ++j);

    The above code fragment produces the following output:i++ produces 3

    ++j produces 4

    Example 3:int sum = 0;int counter = 10;

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    3/6

    3

    sum = ++counter ;

    System.out.println("sum: "+ sum " + counter: " + counter );

    This program fragment will print:

    sum: 11 counter: 11

    This fragment requires careful inspection:The ++ operator is now a prefix operator.Now, counter is incremented before the value it holds is used.The assignment statement is executed in two steps:

    1. Evaluate the expression on the right of the = the value is 11(because counter is incremented before use.)

    2. Assign the value to the variable on the left of the = sum gets 11.

    The next statement writes out: sum: 11 counter: 11

    2. Write a piece of code that provides output based on the age of an infant.If the age is 1, then the output should be One year old, if age is 2, weobtain Two years old and if age is 3, we get Three years old.Otherwise, we should get the message Not a baby!. The age should be

    input via the keyboard using Scanner.

    3. Use an if statement to exchange the value of two integer variables, xand y, but only if x is greater than y . After this if statement has beenexecuted, we ensure that the value of x is definitely less than or equal tothe value of y.

    4. The code below makes use of nested ifs, rewrite it using if else-if.Discuss any drawbacks associated with the if else-if solution.

    import java.util.*;

    public class Scholarship {

    public static void main(String[] args) {

    int mark;

    Scanner myscanner = new Scanner(System.in);

    System.out.println("Type the value of mark");

    //Prompt and read input//

    mark = myscanner.nextInt();if (mark >= 85)

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    4/6

    4

    {System.out.println("High Distinction");if (mark >= 95)

    System.out.println("Consider applying for a

    scholarship");

    }

    myscanner.close();}

    }

    5. Write down a piece of code which tests whether an integer number iswithin the range 5 and 10 (both inclusive) and returns a correspondingrelevant message in case the above condition holds or not.

    The Java compiler may find two types of errors: Syntax Errors andSemantic Errors.

    Common Types of Errors (To be read at home. Will be treated in detailslater.)

    Syntax Errors

    If you make a typing mistake while entering or editing your program, thecompiler may print out a syntax error. This happens when something youtyped doesn't conform to the rules of the Java language. For example, thelanguage specifies that each statement in Java must be terminated by a

    semicolon. If in Lesson 2 we forgot the semicolon on the statement that prints"Hello World!", we might see the following error message when compiling:

    HelloWorld.java:13: ';' expectedConsole.println("Hello world")

    ^1 error

    This error states that the problem was found on line 13 and that a ';' wasexpected but not found.

    Another common syntax error is misspelling the name of a variable or method.For example, if you wrote printline rather than println in the above code, you

    would see the following upon compiling:

    HelloWorld.java:13: cannot resolve symbolsymbol : method printline (java.lang.String)location: class com.otherwise.jurtle.Console

    Console.printline("Hello world");

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    5/6

    5

    ^1 error

    An error message saying it couldn't resolve a symbol usually means that you

    misspelled or misremembered a variable name, method name, or a keyword.

    Semantic ErrorsEven though your program may be syntactically correct, the compiler maydiscover a semantic error (i.e., an error in usage). One example would be if your program tried to use a variable that has never had an initial value set.

    For example, if you had the following code snippet:

    public void runTurtle(){

    int j;

    Console.println(j);}

    The compiler would complain:

    Test.java:12: variable j might not have been initializedConsole.println(j);

    ^1 error

    Cascading Errors

    Cascading errors are not a distinct category of errors like syntax and semanticerrors. Nevertheless, this is a situation worthy of some discussion. Sometimesone error in your program will result in an ambiguity that the compiler cannot

    resolve. This may result in several other error messages on the same line orlater lines that may not represent true errors in the code.

    For example, in the ASimpleSquare example file there is a for loop. If thekeyword for is accidentally mistyped as in:

    fo ( int i = 0; i < 4; i++ )

    {

    forward( 60 );right( 90 );

    }

    The compiler will generate something like:

    ASimpleSquare.java:24: '.class' expectedfo ( int i = 0; i < 4; i++ )

  • 8/8/2019 CSE 2001Y Lab Sheet 2 - Problems

    6/6

    6

    ^ASimpleSquare.java:24: ')' expected

    fo ( int i = 0; i < 4; i++ )^

    ASimpleSquare.java:24: not a statement

    fo ( int i = 0; i < 4; i++ )^

    ASimpleSquare.java:24: ';' expectedfo ( int i = 0; i < 4; i++ )

    ^ASimpleSquare.java:24: unexpected type

    required: valuefound : class

    fo ( int i = 0; i < 4; i++ )^

    ASimpleSquare.java:24: cannot resolve symbol

    symbol : variable ilocation: class ASimpleSquare

    fo ( int i = 0; i < 4; i++ )^

    6 errors