Thursday, August 11, 2011

Assignment 10


Exercise 4
a)
import java.util.Scanner;
public class Division2{
   public static void main(String[] args){

      Scanner stdIn = new Scanner (System.in);
      boolean zero = true;
      double n;
      int d = 0;
       
      System.out.print("\nEnter numerator: ");
      n = stdIn.nextDouble();
       
      System.out.print("Enter divisor: ");
      d = stdIn.nextInt();      
       
      if (d ==0){
         do{
            System.out.print("Enter divisor: ");
            d = stdIn.nextInt();
            zero = false;
            }
         while(d == 0);
        }  
       
        System.out.println(n / d);
    }
}

b)
import java.util.Scanner;
import java.util.*;
public class Division2b{
    public static void main(String[] args){
        Scanner stdIn = new Scanner (System.in);

        boolean ok = true;
        int n;
        int d = 0;
        int result;  
       
        System.out.print("Enter numerator: ");
        n = stdIn.nextInt();
        System.out.print("Enter divisor: ");
        d = stdIn.nextInt();  
       
        do{
            try{
                result = n/d;
                System.out.println(result);
                ok = true;
            }
            catch (ArithmeticException mistake){  
                System.out.print("Invalid Entry. Enter divisor: ");
                d = stdIn.nextInt();
                ok = false;
            }
        }
       while(ok == false);
    }
}



Exercise 5)
import java.util.*;
import java.io.*;

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

   Scanner stdIn = new Scanner(System.in);
   Scanner fileIn;
   int numWords = 0;

   try{
      //Added Code
      System.out.print("Enter full pathname of file: ");
      fileIn = new Scanner(new FileReader(stdIn.nextLine()));


      while (fileIn.hasNextLine()){
         String file = fileIn.next();
         numWords++;
         }


      System.out.println("Number of words = " + numWords);
      }

   catch(FileNotFoundException e){
      System.out.println("Invalid Filename");
      }
   catch(Exception e){
      System.out.println("Error reading from the file.");
      }
   }
}

No comments: