exam

posted Apr 16, 2014, 2:11 AM by Dlovan ismail   [ updated Apr 16, 2014, 2:12 AM ]
/*

Write a program using switch case to do the following:

Note: You must enter a number to represent the case of the switch

1. write a program which reads string from the JOptionPane then put it in a text file (computer.txt)
2. Write a function named (search) that take one argument (type string) represent path of the file and to do counts the number of times the character ’e’ appears in the text file then  prints that number on the screen.
Note: if the character ’e’ not appears in the text file must be print "the character ‘e’ is not found"
3. Write a function named (Sum_Prime) which prints 10 prime numbers randomly between (5-100) and print their total.
*/

 

package exam2;

import java.io.*;

import java.util.*;

import javax.swing.JOptionPane;

 

public class Exam2

{

 

    public static void main(String[] args)throws IOException

    {

        System.out.print("Please choose one of them 1,2 or 3 : ");

        Scanner ch=new Scanner(System.in);

        switch(ch.nextInt())

        {

            case 1:PrintWriter output =new PrintWriter("computer.txt");

                output.println(JOptionPane.showInputDialog("Enter your String :"));

                output.close();

                break;

            case 2:Search("d:computer.txt");

                break;

            case 3:Sum_Prime();

                break;

            default :System.out.println("invalid number");

        }

    }

   

   static void Search(String Path)throws IOException

   {

       Scanner input=new Scanner(new File(Path));

       int count=0;

       while(input.hasNextLine())

       {

           String str=input.nextLine();

           for (int i = 0; i <str.length(); i++)

               if(str.charAt(i)=='e')

                   count++;

       }

      

       if(count!=0)

           System.out.println("the character ’e’ appears in the text file "+count+" times");

       else

           System.out.println("the character ‘e’ is not found");

   }

  

   static void Sum_Prime()

   {

       int count=1,sum=0;

       Random rand=new Random();

      

       while(count<=10)

       {

           int p=rand.nextInt(96)+5;

           boolean flag=true;

           for (int i = 2; i <p; i++)

               if(p%i==0)

                   flag=false;

          if(flag)

          {

              System.out.println(p);

              sum+=p;                  

              count++;

          }

       }

      

       System.out.println("Sum all prime numbers="+sum);

   }

}

Comments