Answers to exercises and questions in Java Course Material

The following are answers to exercises and questions in Java Course Material.

Answers To Exercises In Getting Started With Java

Here are the answers to exercises given in Getting Started With Java Course materials.
  1. Write a program to take a number from user and display whether it is perfect number
  2. Accept ten numbers from user and display the largest of the given numbers
  3. Accept two numbers and display the GCD of the numbers
  4. Display first 10 Fibnoacii numbers
  5. Accept two numbers on command line and raise base (first number) to power (second number)
  6. Accept a number and display its highest factor
  7. Accept a number and display the digits in the reverse order
  8. Create a function that takes a set of integers using varying length argument and returns the average of all the numbers.
  9. Create an array of 10 elements. Read values from keyboard and fill the array. Interchange first 5 elements with last 5 elements and display the array..
  10. Display palindrome numbers in the range 100 to 1000

Answers To Exercises In Java Student's Guide

Here are the answers to exercises given in Java Students' Guide Course materials.
  1. Accept a file and count number of lines in the given file.
  2. Accept a file and display only non-blank lines of the file.
  3. Accept path for a folder and displays all its files and folders
  4. Accept a file from user and display its content in reverse order - first line last and last line first
1.Write a program to take a number from user and display whether it is perfect number
// Perfect Number

import java.util.Scanner;
public class PerfectNumber {
    public static void main(String[] args) {

        // take numbers from user
        Scanner s = new Scanner(System.in);
        int num = s.nextInt();
        int sum = 0;
        for ( int i = 1;  i <= num/2 ; i ++) {
          if ( num % i == 0 ) {
               sum += i;
          }
        }
        if ( sum == num)
              System.out.println("Perfect Number");
        else
              System.out.println("Not Perfect Number");
    }
}

2.Accept ten numbers from user and display the largest of the given numbers
// Accept ten numbers from user and display the largest of the given numbers.

import java.util.Scanner;

public class LargestNumber {
    public static void main(String[] args) {
        // take number from user
        Scanner s = new Scanner(System.in);
        int num, largest = 0;
        
        for ( int i = 1; i <= 10 ;i ++) {
         System.out.print("Enter a number : ");
         num = s.nextInt();
         if ( num > largest)
              largest = num;
        }
        System.out.println("Largest Number : " + largest);
    }
}

3. Accept two numbers and display the GCD of the numbers
// Accept two numbers and display the GCD of the numbers

import java.util.Scanner;
public class GCD {
    public static void main(String[] args) {
        // take numbers from user
        Scanner s = new Scanner(System.in);
        int first = s.nextInt();
        int second = s.nextInt();
        
        int i = first < second ? first : second;
        
        for ( ;  i > 0 ; i --) {
          if ( first % i == 0 &&  second % i == 0) {
               System.out.println("GCD = " + i);
               break;
          }
        }
    }
}

4. Display first 10 Fibnoacii numbers
// display Fibonacii series 
public class Fibonacii {
    public static void main(String[] args) {
        int first = 1,second = 1, result;
        
        System.out.println(first);
        System.out.println(second);
        
        for ( int i = 3; i <= 10 ; i ++) {
             result = first + second;
             System.out.println( result );
             first = second;
             second = result;
        } // for
    } // end of main
}

5. Accept two numbers on command line and raise base (first number) to power (second number).
// Accept two numbers on command line and raise base (first number) to power (second number).

public class Power {
    public static void main(String[] args) {
        int base = Integer.parseInt( args[0]);
        int power  = Integer.parseInt( args[1]);
        int result =1;
        for ( int i = 1; i <= power ; i ++) {
              result *= base;
        }
        System.out.printf("%d raised to %d = %d", base, power, result);  
    }
    
}


6. Accept a number and display its highest factor
import java.util.Scanner;

public class HighestFactor {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = s.nextInt();

        for ( int i = num/2; i > 0 ; i --) {
            if ( num % i == 0 ) {
                System.out.printf("Highest Factor : %d\n",i);
                break;
            }
        }

    }
}

7. Accept a number and display the digits in the reverse order

import java.util.Scanner;

public class ReverseDigits {


    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = s.nextInt();

        while( num != 0 )
        {
            System.out.print( num % 10);
            num /= 10;

        }

    }

}

8. Create a function that takes a set of integers using varying length argument and returns the average of all the numbers.

public class AverageOfNumbers {


    public static void main(String[] args) {
       System.out.println( average(10,20,45,33));
       System.out.println( average(12,22,88));
    }

    public static int average(int ... numbers) {
        int total = 0;
        for(int n : numbers)
            total += n;

        return total / numbers.length;
    }
}


9. Create an array of 10 elements. Read values from keyboard and fill the array. Interchange first 5 elements with last 5 elements and display the array.

import java.util.Scanner;

public class InterchangeArray {


    public static void main(String[] args) {

            int a[] = new int[10];

            Scanner s = new Scanner(System.in);

            // read values from keyboard into array
            for ( int i = 0 ; i <  a.length ; i ++) {
                System.out.printf("Enter a number for [%d] element :",i);
                a[i] = s.nextInt();
            }

            System.out.println("Orginal Array");
            printArray(a);

            // interchange array
            for ( int i = 0, j = a.length -1 ; i < a.length / 2; i ++, j --) {
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }

            System.out.println("Interchanged Array");
            printArray(a);
        

    }

    public static void printArray(int [] a) {
            for(int n : a) {
                System.out.printf("%5d",n);
            }
    }

}


10. Display palindrome numbers in the range 100 to 1000

public class PalindromeNumbers {

    public static void main(String[] args) {

        for ( int i = 100; i <= 1000; i ++)  {

              int n = i, rn  = 0;
              while (n > 0 ) {
                  int d = n % 10;  // get right most digit
                  rn = rn * 10 + d;
                  n /= 10;   // remove right most digit
              }
              if ( i == rn )
                  System.out.println(i);
        }

    }

}

Accept a file and count number of lines in the given file.
import java.io.FileReader;
import java.util.Scanner;

public class CountLines {
    
    public static void main(String[] args) throws Exception {
        
        System.out.println("Enter a filename : ");
        Scanner s = new Scanner(System.in);
        String filename =  s.nextLine();
        
        FileReader fr = new FileReader(filename);
        int ch = fr.read();
        int nolines = 0;
        while ( ch != -1) {
             if ( ch == '\n')
                    nolines ++;
             ch = fr.read();
        }
        fr.close();
        System.out.printf("No. of lines =  %d\n",nolines);
        
    }
    
}

Accept a file and display only non-blank lines of the file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class NonBlankLines {
    
    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);
        String filename =  s.nextLine();
        FileReader fr = new FileReader(filename);
        BufferedReader br  = new BufferedReader(fr);
        String line = br.readLine();     
        while ( line != null) {
             if ( line.trim().length() > 0 )
                   System.out.println(line);
             line = br.readLine();
        }
        br.close();
        fr.close();
    }
    
}

Accept path for a folder and displays all its files and folders
import  java.io.*;
import  java.util.Scanner;

public class FileList
{
 public static void main(String args[])
 {
  Scanner s = new Scanner(System.in);
  System.out.println("Enter directory name :");
  String dir = s.nextLine();
  File path = new File(dir);
  if (! path.isDirectory())
  {
     System.out.println( dir + " is not a directory");
     return;
  }
  File list [] = path.listFiles();
  for ( File f : list)
  {
     if ( f.isDirectory())
      System.out.println(f.getName() + "\t" +  "");
     else
     System.out.println( f.getName() + "\t" +  f.length());
  } // end of for loop 
 } // end of main
} // end of class 
    

Accept a file from user and display its content in reverse order - first line last and last line first.
import java.util.*;
import java.io.*;

public class  ReverseFile
{
   public static void main(String args[])  throws Exception  {

     System.out.println("Enter a filename : ");
     Scanner keyboard = new Scanner(System.in);
     String filename =  keyboard.nextLine();
        
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     
     Stack s = new Stack();
     String line = br.readLine();
     while ( line != null ) {
       s.push(line);
       line = br.readLine();
     }
     br.close();
     
     // display stack until it is empty
     while ( ! s.empty())
          System.out.println( s.pop());

  }
}

Answers To Questions In Java Examination

Here are the answers to questions given in Java Examination at the end of Java Student's Guide.

Question No. Correct Answer
1 c
2 d
3 d
4 c
5 a
6 c
7 c
8 a
9 d
10 d
11 a
12 c
13 a
14 c
15 d
16 c
17 c
18 c
19 d
20 d
21 b
22 c
23 c
24 b
25 d
26 b
27 d
28 c
29 c
30 b
31 b
32 c
33 a
34 c
35 d
36 b
37 d
38 b
39 b
40 a
41 d
42 a
43 a
44 b
45 a
46 c
47 a
48 d
49 a
50 c

 

More on: public and java
File uploaded by Go FTP FREE Client