Likes

Java Lab_11_Ans_1

James is employed as a software Developer at AxisPro Technologies. He has been assigned the task to creat the fill in the blanks game for kids. The menu of the game should provide the following options:
1- Play
2- Instructions
3- Quit

SOLUTION


import java . io . BufferReader;
import java . io . BufferedWritter;
import java . io . FileReader;
import java . io . FileWriter;
import java . util . Scanner;

public class Game {

public void showMenu () {
 int option;
 Scanner sc = new Scanner (System . in);

 System.out.println (-----------Menu----------");
 System.out.println ("1. Play");
 System.out.println ("2. Instruction");
 System.out.println ("3. Quit");
 System.out.println ("\nChoose the option: ");

 option = sc . nextInt ();

 switch (option) {
   case 1:
         playGame ();
         showMenu ();
         break;
   case 2:
         instructionsGame ();
   
         break;
   case 3:
        System . exit (O);
        break;
    default:
        showMenu ();
        break;
     }
}

public void playGame () {
  String name, catg;
  int size, flag = O, count = O, cont = O, score = O;
  Scanner sc = new Scanner (System . in);
  StringBuffer guess = new StirngBuffer ();
  StringBuffer wrgString = new StringBuffer ();
  StringBuffer rgtString = new StringBuffer ();

 System.out.println ("Enter your name: ");
 name = sc . nextLine () . toUpperCase ();

 try (BufferedReader br = new BufferedReader (new FileReader ("Master . txt "))) {
        Sturng s;
        System.out.println ("The categories are: ");
 
       while ((s = br . readLine () ) != null) {

         System.out.println (s);
     }

    System.out.println ("\nEnter the name of the category: ");
       catg = sc . nextLine () . toUpperCase ();

       try (BufferedReader br1 = new BufferReader
      (new FileReader (catg + ".txt"))) {
     
       while ((cont !=1) ) {

     count = O;
      if ((s = br1 . readLine () ) == null)
      System.out.println ("You have guessed all the words correctly");
                      try {
                            FileWriter fos = new FileWriter ("Score . txt ", true);
                             BufferedWriter bw = new BufferedWriter (fos);
                           bw . newLine ();
                           bw . write (name + ", Score = " +
        score);
                           bw . close ();
                           fos . close ();
                        } catch (Exception e) {
                        }
                        System.out.println
     (name . toLowerCase () + ", your total score is " + score);
                              showMenu ();
                          }
                          size = s . length ();

                           guess = new StirngBuffer ();
                           rgtString = new StirngBuffer ();
                           wrgStirng = new StringBuffer ();
                           for (int j = O; j < size; j++) {
                                 System.out.print (" _ ");
                                 guess . append ("_");
                                  rgtString . append (s . charAt (j) + "
                        ");
                                }
                              while (true) {
                                 flag = O;
 
                              System.out.println ("\n\nEnter your guess: ");
                              String ch = sc . nextLine ();
                              ch = ch . toUpperCase ();

                             for (int i = O; i < size; i++) {
                               if (s . charArt (i) == ch . charAt
                    (O)) {
                            String tmp = String . valueOf (s .charAt (i) );

                              guess . replace (i * 2, (i * 2) + 1, temp);
                                        flag = 1;
                                     }
                                }
                                 if (flag == O) {
                                    wrgString . append (ch + ", ");
                                    System.out.println ("\nMisses: "+ wrgString);
                                       count++;
                                    }
                                    if (count == (s . length () / 2) )
                                      System.out.println ("You lost your all chances");
                                          cont = 1;
                                          try {
                                          FileWriter fos = new FileWriter ("Score . txr ", true);
                                           BufferWriter bw = new BufferWriter (fos);
                                             bw . newLine ();
                                             bw .write (name + ", Score = " + score);
                                           
                                              bw . close ();
                                              fos . close ();
                                             } catch (Exception e) {
                                             }
                                             System.out.println
                                        (name . toLowerCase () +", your total score is " + score);
                                                break;
                                             }
                                          }
                                     }
                                  }catch (Exception e) {
                                  }
                             } catch (Exception e) {
                             }
                   
                             public void instructGame () {
                               System.out.println ("---------------
                          Instructions--------------");
                                System.out.println ("1. Yoy need to guess letters for the row of dashes");
                                System.out.println ("2. If you guess the correct letter, it will appear in the next statement");
                                System.out.println ("3. If you guess the incorrect letter, it will appear in the list of missed letter.");

                               System.out.println ("4. If you guess the word correctly, you will score 10 points.");
                               System.out.println ("5. If you guess the word incorrectly, the game will be terminated");
                                   showMenu ();
                               }

                            public static void main (Stirng [] args) {
                              Game obj = new Game ();
                              obj . showMenu ();
                         }
                     }
                                

Java Lab_10_Ans_2

Write a program to create a class to handle the enquiry details to tourism. The class should provide the following functionalities:
- A menu should be displayed that allows the user to intiate enquiry, view enquiry, and exit the menu.
-If the option to intitate enquiry is selected, the program should allow the user to enter the enquiry details, such as name, contact number, address, enquiry category, and description of the enquiry. In addition, the enquiry categories will be Prices, Locations, and packages. Further, the entered details should be stored in the Enquiry.txt file.
-If the option to view query details is selected, the name of the user, whose details need to be viewed, should be entered. If the name exists in the Enquiry.txt file , the details should be displayed. Otherwise, an error message should be displayed.
- If the option to exit menu is selected, the program must terminate.



SOLUTION 





import java . io . BufferReader;
import java  . io . BufferReader;
import java . io . FileReader;
import java . io . FileWriter;
import java . io . Scanner;

public class EnquiryForm
{

String enquiryrDetails [] = new String [5];

public void showMenu () {
int option;
Scanner sc = new Scanner (System . in);

System.out.println ("\n-----------Menu-----------");
System.out.println ("1. Initiate Enqiury");
System.out.println ("2. View Enquiry");
System.out.println ("3. Exit");
System.out.println ("\nChoose the option: ");

 option = sc . nextInt ();

 switch (option) {
    case 1:
       intEnq ();
       showMenu ();
       break;
    case 2:
        viewEnq ();
        showMenu ();
        break;
    case 3:
         exitMenu ();
         break;
      default:
        System.out.println ("Incorrect menu option");
          showMenu ();
          break;
      }
   }

 public void initEnq () {
 
  char choice = 'y';

 do {
      Scanner sc = new Scanner (System . in(;
      System.out.println ("Enter Name: ");
      enquiryDetails [0] = sc . nextLine () . to LowerCase () + ",";
   
      System.out.print ("Enter Contact No: ");
      enquiryDetails [1] = sc . nextLine () + ",";
      System.out,print ("Enter Address: () + ",";
      System.out.print ("Enter Enquiry Category
   (Prices/Local/Packages) : ");
     enquiryDetails [3] = sc . nextLine () + ",";
    System.out.print ("Enter Enquiry Description: ");
     enquiryDetails [4] = sc . nextLine () + ",";
 
      try {
          FileWriter fos = new FileWriter
   ("Enquiry . txt ", true);
               BufferedWWriter bw = new BufferedWriter
    (fos);
            for (int i = 0; i < enquiryDetails . length
    i++) {

             bw . write (enquiryDetails [i]);
         }
           bw . newLine ();
           bw . close ();
          fos . close ();
      } catch (Exception e) {
        System.out.println (e);
      }
      System.out.print ("\nDo you want to initiate more enquiry: ");
      String ch = sc . next () . toLowerCase ();
       choice = ch . charAt (0);
    } while (choice == 'y');
 }
    public void viewEnq () {
   Scanner sc = new Scanner (System . in);
   String name;
   int flag = 0;
   System.out.print("Enter the name of the user to view the details: ");
    name = sc . nextLine () . toLowerCase ();
   try (BufferedReader br = new BufferedReader(new
FileReader("Enquiry.txt ")))    {
            String s;
            while ((s = br.readLine())  != null)   {
               String plitData[] = s.split(",");
             if (splitData[O].equals(name))    {
                 System.out.println("Enquiry Detail:");
                 System.out.println
("=================================")
                  System.out.println("Name:
 " + splitData[O] );
                  System.out.println("contact No:
" + splitData[1] );
                  System.out.println("Address:
" + splitData[2] );
                  System.out.println("Enquiry Catagory:
" + splitData[3] );
                   System.out.println ("Enquiry Description: " + splitData [4]);
               System.out.println
 ("===================================");
           flag = 1;
        }
    }
      if (flag == 0) {
       System.out.println (name + " does not exists");
      }
    } catch (Exception e) {
    }

    public void wxitMenu () {

     System.exit (0);
}
   public static void main (String [] args) {
    EnqiuryForm obj = new EnquiryForm ();
    obj . showMenu ();
}

Java Lab_10_Ans_1

Write a program to accept two numbers and perform division, the program should provide the functionality such that if a usertries to divide the number by 0, the program should terminate with a customized message.

SOLUTION





import java . util . Scanner;

public class Divison {

 public static void main (String args []) {
   
  int num1, num2, result;
  Scanner input = new Scanner (System . in);
  System.out.println ("Enter the 1st number");
  num1 = input . nextInt ();

 System.out.println ("Enter the 2nd number");

 num2 = input . nextInt ();

 try {

   result = num1 / num2;
   System.out.println ("The result is " + result);

 } catch (ArithmeticException e) {

 System,out.println ("Divison by zero not Possible! ");
  }

 }

}

java Lab09_Solution2.

David has been assigned a task of creating an application to store the employee details. For this, David decided to display the following menu when the application starts:

1.  Entry Data
2.  Display Data
3.  Exit

Thereafter, he decides to implement the following functionalities:

-When a user selects the option to entry data, the employee details. such as employee ID, employee name, department, designation, date of joining, date of birth, marital status, and date of marrige, should be captured. In addition, a functionality to add more records should be implemented.

-When a user selects the option to display the data, the stored data muust be displayed.

-When a user selects the option to exit, the application must be terminated. Further, David needs to implement user- defined exceptions for the following cases:

- If the menu input entered by the user is other than1,2,or3, an appropriate message should be displayed to the user and the application must restart.

- If the employee ID does not start with the aplhabet, e or E, an appropriate message should be displayed to the user and the application must terminate.

Help David to implement the preceding functionalities.


SOLUTION


1- Create a Java application, Lab09_Solution2.
2- Create a class, SelectionExeption, in the Java application, Lab09_Solution2.
3- Replace the exiting code in the SelectionException.java file with the following code:

class SelectionException extands Exception  {

selectionException ()   {
System.out.println("Invalid input, Please select a valid menu option");

}
}
4- Create a class, PatternException, in the Java application, Lab09_Solution2.
5- Replace the exisiting code in the PatternException.java file with the following code:

public class PatternException extends RuntimeException  {

public PatternException()  {

System.out.println("Invalid pattern for Employee ID...");
}

public PatternException(String msg)   {
super(msg);
}
}
6- Create a class, EmployeeDetails, in the Java application,Lab09_Solution2.
7- Replace the existing code in the EmployeeDetails.java file with the following code:

import java.until.Scanner;

public class EmployeeDetails  {

String employeeDetails[] [] = new String[100] [8];

public void showMenu () throws SelectionException  {
   int option;
Scanner sc = new Scanner (System.in);

System.out.println("----------Menu--------");
System.out.println("1. Entry Data");
System.out.println("2. Display Data");
System.out.println("3. Exit");
System.out.print("\nchoose the option: ");

option = sc.nextInt() ;

Java Lab_8_Ans_5

CREATE A PROGRAM THAT SEARCHES A TEXT FILE BY USING REGULAR EXPRESSIONS.


SOLUTION


Create a simple applications that will loop through a text file(gettys.html) and search for
text by using regular expresions. If the desired text found on a line, print out the line number
and the line text.
9 <h4>Abrahan Lincoln</h4>
10 <h4>Thrusday, November 19, 1863</h4>

Tasks
 The gettys.html file is located in the root of the project folder. To examine the file,
with the project open, click the file tab. Double-click the file to open it and exmaine its
content.
   1. Edit teh FindText.java file.
   2. Create a pattern and a Matcher field.
   3. Generate a Matcher based on the supplied Pattern object.
   4. Search each line for the pattern supplied.
   5. Print the line numver and the line that has matching text.
   6. Run the FindText.java file and search for these patterns.
              All lines that contain <h4>
              All the ines that contain the word "to" (For example, line 17 should
              not be selected.)
              All the lines that start with 4 spaces'
              Lines that bedin with "<p" or "<d"
              Lines that only contain HTML closing tags( for example, "</div>")
                 
Open the StringPractice02 project and make the followng changes. Please note that the
code to read a file has been supplied for you.
    1. Edit the FindText.java file.
    2. Create fields for a Pattern and a Matcher object
       private Pattern pattern;
       private Matcher m;
    3. Outside the search loop, create and initialize your pattern object.
       pattern = pattern.compile("<h4>");
    4. Inside the search loop, generate a Matcher based on the supplied Pattern
       object.
      m = pattern.matcher(line);
    5. Inside the search loop, search each line for the pattern supplied. print the line
       number and the line that has matching text.
       if (m.find() )  {
           System.out.println(" " + " "+ line);
       }
   6. Run the FindText.java file and search for these patterns.
              All the lines that contain <h4>
              pattern = Pattern.compile("<h4>");
             
             All the lines that contain the word "to" (For example, line 17 should
             not be selected.)
     
             pattern = Pattern.compile("\\bto\\b"0;
       
             All the lines that start with 4 spaces
             
            pattern = Pattern.compile("^\\s{4}");

            Lines that begin with "<p" or "<d"
 
            pattern = Pattern.compile("^<[p|d]");

            Lines that only contain HTML closin tags(For example, "</div>")
 
            pattern = Pattern.compile("^</.*?>$");

Java Lab_8_Ans_4

Paras comma-delimited text and convert the data into Shirt objects.

SOLUTION



you have been given some comma-delimated shirt data . parse the data . store it in shirt
objects and print the results. the output from the program should like the following.

=== Shirt List ===

Shirt ID: S001

Description: Black Polo Shirt

Color: Black

Size: XL

Shirt ID: S002

Description: Black Polo Shirt


Color: Black

Size: L

Shirt ID: S003

Description: Blue Polo Shirt

Color: Blue

Size: XL

Shirt ID: S004

Description: Blue Polo Shirt

Color: Blue

Size: M

Shirt ID: S005

Description: Tan Polo Shirt

Color: Tan

Size: XL

Shirt ID: S006

Description: Black T-Shirt

Color: Black

Size: XL

Shirt ID: S007

Description: White T-Shirt

Color: White

Size: L

Shirt ID: S008

Description: White T-Shirt

Color: White

Size:L

Open the StringPractice01 project and make the following changes.

1 Edit the main method of the StringSplitTest . java file.

2 Parse each line of the shirts array. Create a shirt object for each
  line and add the shirts to a List. A for loop tp perform
  these steps could be as follows.

   for (Stirng curLine:shirts){
     String[] e = curLine . split(",");
     shirtList . add(new Shirt(e[0], e[1], e[2], e[3] ) );
  }

3 Print out the list of shirts. A loop to do this could be like the
  following.

  System.out.println("=== Shirt List ===");
  for (Shirt shirt:shirtsList){
    System.out.println(shirt . toString() );
  }

4 Run the StringSplitList . java file and verify that your output is similar

Java Lab_8_Ans_3

Write a program to accept the date from the user and validateit according to the format, DD/MMYYYY or D/M/YYYY. In addition, the year should be from 1900 to 2099.


SOLUTION



import java . util . Scanner;
import java . util . regex . Matcher;
import java . util . regex . Pattern;

 public class DateValidator {

 private Pattern pattern;
 private Matcher matcher;
 private static final String DATE_PATTERN = " (0 ? [1-9] | [12] [0-9] | 3 [01] ) / (0 ? [1-9] | [012] ) /
             ( ( 19 | 20) \\ d\\d)";
     public DateValidator () {
       pattern = Pattern . compile (DATE _ PATTERN);
  }
   
     public boolen validate (final String date) {
 
     matcher = pattern . matcher(date);

     if (matcher . matches () ) {
   
        matcher . reset ();

     if (matcher . find () ) {

          String day = matches . group (1);
          String month = matcher . group (2);
          int year = Integer . parseInt (matcher . group
     (3) );
            if (day . equals ("31")
                   && (month . equals ("4") ||
   month . equals ("6") || month . equals ("9")
         
       || month . equals ("11") || month . equals ("04") || month . equals ("11") .
       
        || month . equals ("09") ) ) {
       return false; // only 1,3,5,7,8,10,12 has 31 days
        } else if (month . equals ("2") ||
   month . equals (:02") ) {
                              // leap year
                            if (year % 4 == 0) {
                            if (day . equals ("30") ||
           ("31") ) {
                          return false;
                      } else {
                                return true;
                      } else {
                             if (day . equals ("29") || day . equals
               ("30") || day . equals ("31") ) {
                                               return false;
                                             } else {
                                                   return true;
                                             } else {
                                          }
                                       }
                                 } else {
                                       return true;
                                    }
                               } else {
                            }
                                 return false;
                        }
                              } else {
                                  return false;
                           }
                       }
                             
                       public static void main (String [] args) {
                        DateValidator dv = new ateValidator ();
                         boolen status;
                          do {
                               Scanner sc = new Scanner (System. in);
                               String dt;

                               System.out.println ("Enter the date: ");
                               dt = sc . next ();
                       
                               status = dv . validate (dt);
                                if (status) {
                                      System.out.println ("Date is in correct format");
                                          } else {
                                              System.out.println ("Date is not in correct format");
                                            }
                                         } while (status == false);
                                    }
                                }