CECS 174  FINAL EXAM PRATICE

1. What is wrong with the following program? How would you fix this code?
     public class Test
     {  public static void main(String [ ] args)
          { int index;

             boolean found;

             for(index = 0; index < 10 && !found; index++)
                  { if ( index > Math.PI)
                        {System.out.println (index + “ is greater than Pi”);
                            found = true;
                         }
                    }
              }
       }
       Answer:

       The variable named found is not initialized before being used. This results in a
       compiled-time error. You must set this variable to false for this program to compile
       and work as intended. [4 points]

2. Circle 0 if the expression evaluates to 0 (false), or 1 (true) if the expression evaluates to 1 (true).

  int count = 0, limit = 10;

    0    1    1.  ! (count = = 12)                          

    0    1    2.  ( 5 && 7) + (!6)                         

    0    1    3.    !( ((count < 10 ) | | (x < y)) &&  (count > = 0) )      

    0    1    4.    (limit < 20)  | | (limit/count) > 7)                                      

    0    1    5.   !count

Answer  1. 1  2. 1  3. 0  4. 1  5.  1

3. Given the following code snippet: 

     int myInt = 3;
     if (myInt < 5)
          if (myInt < 3)
               System.out.println(“< 3”);
     else
          if (myInt > 2)
               System.out.println(“>2”);
     else
          System.out.println(“Other”);

     What will appear in the standard output? [ 3 points ]
    
     Answer:     >2

 

4.  For each question below, do you think the two Java expressions will produce the same result of hotF ? Explain your answer.

a.      hotF  = 9.0* hotC/5.0  +32.0;

         hotF = 9.0/5.0*hotC + 32.0

Answer: The two expressions will produce the same result. Both expression use the double data type.

b.     hotF = 9.0*hotC/5.0 + 32.0

       hotF = 9/5*hotC +32.0

Answer: The two expression did not produce the same result because the second expression uses 9/5 which result in 1.

5.  Write a program that is using  a loop to read in a list of odd numbers (such as 1  -3  7  9 ) and compute the total of the numbers on the list. The user should be able to create any list of many different odd numbers.

Answer:
import iopack.Io;
public class Test
{ public static void main (String [] agrs )
{ int sum = 0, next;
System.out.println("Enter a list of odd numbers. Place an even number at the end of the list.");
next = Io.readInt(""); // //You can use JOptionPane.showInputDialog to input
while ( ( next %2) != 0 )
{ sum += next;
  next = Io.readInt("");
}
}

6.  What would be the while-loop statement equivalent of the for-statement below.
         for( i = 0 ;  ;  i ++)
               System.out.println("hello");
[3 points]
Answer:     i =0;
                  while( 1 )
                  { System.out.println("hello");
                     i++;
                  }

7. Write a program that is using loop statements to display an output below.

1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
1234567891011
123456789101112
12345678910111213
1234567891011121314
123456789101112131415
12345678910111213141516
1234567891011121314151617
123456789101112131415161718
12345678910111213141516171819
1234567891011121314151617181920

Answer:

public class Test
{ public static void main (String [] agrs )
    { for (int i =1; i <= 20; i ++)
       { for (int j = 1; j <= i; j++)
            System.out.print(j);
           System.out.println("");;
       }
    }
}

 

8. Write a program, when completed, will ask the user to enter 10 integers which are stored in an array, display the numbers entered in ascending order and the average   of these numbers. The function called AvgArray, which you must write, is to calculate and return the average of the numbers entered. Another function called the SortingElement, which you also must write, is to sort the array in ascending order.
Answer:     

import iopack.Io;
public class Test
{ public static void main (String [] agrs )
    { int num [ ] = new int[10];
       for(int i = 0; i < num.length; i++)
           num[i] = Io.readInt("Enter an integer number"); //You can use JOptionPane.showInputDialog to input
       SortingElement(num);
       System.out.println("The average is " + AvgArray(num) );
    }
    public static void sortingArray(int  x[ ])
   {       for(int i=0;i<x.length; i++)
                 for(int j = i+1; j <x.length ; j++)
                         if(x[i] > x[j])
                          {int temp;
                             temp = x[i];
                             x[i]=x[j];
                              x[j]=temp;
                           }
   }
  public static double AvgArray(int x[ ])
  {    double total = 0.0;
        for(int i=0;i<x.length;i++)
          total += x[i];
                return total/x.length;
   }
}

9. Construct a class Employee which has a name and an  identification number as the data members.. Form a constructor and some appropriate methods for the class Employee.
Write a main method that contains an array of three Employee objects. Pass the array to a method called showEmployee  which will display the employee's  name and identification for each Employee object.

Answer:

public class Employee
{ private String name;
   private int Id;
   public Employee(int id, String n)
   { Id=id;
      name = n;
   }
   public int getId()
   { return Id;
   }
   public String getName()
  { return name;
  }
}
public class Test
{ public static void main(String [] args)
     {  Employee[] stud = new Employee[3];
         emp[0] = new Employee(1,"A");
         emp[1] = new Employee(2,"B");
         emp[2] = new Employee(3,"C");
         displayEmployee(emp, emp.length);
      }
   public static void displayEmployee(Employee[ ] stud, int len)
    {  for (int i = 0; i < len ; i++)
         { System.out.println("EmployeeId " + emp[i].getId() + " " + "Name: " + emp[i].getName());
          }
    }
}
 

10. What is wrong with this class definition? Fix it so it works when you invoke main( ). [4 points]

    public class Avg
   {  pubic static void main(String [ ] args)
          double a = 5.1;
          double b =  20.30;
          double c = 12.5;
           System.out.println( findAvg(a,b,c));
   }
 

    double findAvg(double a, double b, double c)
    { return (a + b + c);
     }
}

 Answer:         What’s wrong here is that the static method attempts to invoke the
                         non-static method named findAvg( ). To fix this, we make findAvg( ) 
                         static.

11. What is the result of trying and compile and run this program?

     public class Test
     { public static void main(String [ ] args)
          {  Test e = new Test( );
               e.test(5.0, 5.0, 3.5); //where L is indicated a long integer
           }
             void test(double a, double b, double c)
             {  System.out.println(“double, double, double”);
              }
              void test(int a, float b, long c)
              {  System.out.println(“int, float, long”);
              }
        }

     Answer:   The code will display  double, double, double.

12. Write a Java code which prints the integer 1234567890 in reverse. Use an array to hold the digits, a While loop statement to extract those digits, and a For loop statement to print those digits in reverse.

  Answer:   
 
  int num = 1234567890;
  int [ ] digits = {0,0,0,0,0,0,0,0,0,0};

  //Extract individual digits from num and store in an array;
     int i = 0;

     while (num !=  0)
     {  digits[i ++] = num % 10;
         num /= 10;
      }
      // Print digits in reverse
     for(i = 0; i < digits.length; i++)
           { System.out.print(digits[i]);}

13.  Modify the Java coding below which changes a string object called author that is written in the form  lastName, firstName   to one that is in the form  firstName  lastName.


String  author = “Nguyen,  Phuong”;
//your coding to store Phuong  Nguyen in a string object called name.

Answer:

 int posComma = author.indexOf(“,  “);
String name =  author.subString(posComma + 2) + “  “ +  author.substring(0, posComma);

14. Write a complete Java program with the following requirements:

  1. Define a method sum2Numbers  with two parameters named num1 and num2. The method returns the sum of num1 and num2.
  2. Call the function sum2Numbes in the main method. Pass two values 10 and 20 to the function sum2Numbers. Display the returned value from the function sum2Numbers.
    Answer

import javax.swing.*;
public class test
{public static void main(String [] args)
{

   int total;

   total = sum2Numbers(10,20);
  System.out.println(“The sum is “ + total);

}
pubic static int sum2Numbers(int num1, int num2)
{int sum;
  sum = num1 +num2;
  return sum;
}

 15. Write a complete Java program with the following requirements:
              a.  Define a method called showMessage that displays a message “Have great
                   holidays”
              b. Define a the main method that called showMesssage method 10 times using a
                  for loop.

              Answer
              import javax.swing.*
              public class test
              {public static void main(String [] args)
                 {  for (int n = 0; n < 10; n++)
                            showMessage( );
                  }
                  public static void showMessage( )
                  {  System.out.println(“Have great holidays”);                  
                   }
                 } 

16. A distribution company uses a two-dimensional array to keep track sales.
 

 

QUARTER 1

QUARTER 2

QUARTER 3

QUARTER 4

EAST REGION

10

30

15

40

WEST REGION

32

45

100

37

SOUTH REGION

29

56

41

33

NORTH REGION

46

38

52

34

 

a. Declare and initialize a two-dimensional array of type float to store the sales.
Answer

doublw sales[][] ={{10,30,15,40},{32,45,100,37},{29,56,41,33},{46,38,52,34}} ;

b.[3 points]  Write an efficient code fragment that computes the yearly sales for South Region

Answer

double sum = 0.0;
for (int q=0; q < 4; q++)
  sum +=   sales[2][q]; // index row 2 means South Region

c. Write an efficient code fragment that finds the region with the highest quarter sales (storing the result in variable bestRegion) and the best quarter (storing the result in variable bestQuarter). Based on the sales data above, the  bestRegion variable will have a value of  1 ( WestRegion) and the bestQuarter variable will have a value of 2 (Quarter 3)

Answer

double highestquatersales = 0;
int bestregion = 0, bestquarter = 0;
for(int r=0; r < 4; i++) // r - region
     for(int q = 0; q < 4; q++) // q - quarter
            if( sales[r][q] > highestquartersales)
                 { highestquartersales = sales[r][q];
                    bestregion = r;
                    bestquarter = q;
                 }
 

d. Write an efficient code fragment that stores the yearly sales for each region in the same one-dimensional array.

Answer

double regionSales[4];
for(int r=0; r < 4; i++) // r - region
     for(int q = 0; q < 4; q++) // q - quarter
            regionSales[r] +=  sales[r][q];

e. double Write an efficient code fragment that stores the region sales for each quarter in the same one-dimensional array.

Answer
float  quarterSales[4];
for(int q=0; q < 4; q++) // q – quarter sales
     for(int r = 0; r < 4; r++) // r- region
           quarterSales[q] +=  sales[r][q];

16.