Java Tutorial - DOC

Document Sample
Java Tutorial - DOC Powered By Docstoc
					Tutorial 0: Java revisit
1. Consider the following method, which interactively reads and writes the identification
number, age, salary (in thousands of dollars), and name of each individual in a group of
employees. How can you improve the program?

import java.util.*;
public class T0Q1 {
public static void main(String[] args) {
  int x1, x2, x3, i;
  String name;
  Scanner sc = new Scanner(;
  x1 = sc.nextInt();
  x2 = sc.nextInt();
  x3 = sc.nextInt();
  while (x1 != 0) {
   name =;
   System.out.println(x1 + " " + x2 + " " + x3 + name);
   x1 = sc.nextInt();
   x2 = sc.nextInt();
   x3 = sc.nextInt();
  } // end while
} // end main

2. What is the problem with the following code fragment?

num = 50;
while (num >= 0) {

3. What can go wrong with the following method? How can you protect yourself?

public static double computation (double x) {
  return Math.sqrt(x)/ Math.cos(x);

4. Using a for loop, write a program that displays the squares of all integers greater than 0
and less than or equal to a given number n.

5. Write a method that computes the sum of the first fifty positive integers in an array of
N arbitrary integers.
6. The following code is supposed to compute the floor of the square root of its input
value x that is non-negative (that is, x >= 0). (The floor of a number n is the largest
integer less than or equal to n.)
a. What output does the program produce when x = 64?
b. When x = 2?
c. The program does not always work. Fix it.

import java.util.*;
public class T0Q6 {
public static void main(String[] args) {
  int x;
  Scanner sc = new Scanner(;
  int result = 0;
  int temp = 0;
  x = sc.nextInt();
  while (temp < x) {
   temp = result * result;
  } // end while
  System.out.println("The floor of the square root of " + x + " is " + result);
} // end main

7. Suppose that, due to some severe error, you must abort a program from a location
deep inside nested method calls, while loops, and if statements. Write a diagnostic
method void severeErrorMessage(int error)
that you can call from anywhere in a program. This method should take an error code as
an argument, display an appropriate error message, and terminate program execution.

Description: This is an example of java tutorials. This document is useful for conducting java tutorials.