Friday, 29 March 2019

Practice Coding Questions for Companies

Count ways to N'th Stair(Order does not matter)

There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
Note: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, an integer N will be given.
Output:
For each testcase, in a new line, print number of possible ways to reach Nth stair.
Constraints:
1 <= T <= 1000
1 <= N <= 106
Example:
Input:
2
4
5
Output:
3
3
Explanation:
Testcase 1:
 There are 3 ways to reach 4th stair.


Solution-
class DynamicProgramming{
    
    // function to find number of ways 
    Long countWays(int m){
        
        // your code here
        m=(m/2)+1;
        Long l=Long.valueOf(m);
        
        return l;
    }   
    
}

Question - Find the smallest positive number missing from an unsorted array

  Input: {2, 3, 7, 6, 8, -1, -10, 15}
 Output: 1

 Input: { 2, 3, -7, 6, 8, 1, -10, 15 }
 Output: 4

 Input: {1, 1, 0, -1, -2}
 Output: 2

Solution-


import java.util.*; 
  
class test
{    
       
    /* Utility function that puts all non-positive  
       (0 and negative) numbers on left side of  
       arr[] and return count of such numbers */
    static int segregate (int arr[], int size) 
    { 
        int j = 0, i; 
        for(i = 0; i < size; i++) 
        { 
           if (arr[i] <= 0)   
           { 
               int temp; 
               temp = arr[i]; 
               arr[i] = arr[j]; 
               arr[j] = temp; 
               // increment count of non-positive  
               // integers 
               j++;   
           } 
        } 
       
        return j; 
    } 
       
    /* Find the smallest positive missing  
       number in an array that contains 
       all positive integers */
    static int findMissingPositive(int arr[], int size) 
    { 
      int i; 
       
      // Mark arr[i] as visited by making  
      // arr[arr[i] - 1] negative. Note that  
      // 1 is subtracted because index start  
      // from 0 and positive numbers start from 1 
      for(i = 0; i < size; i++) 
      { 
        int x = Math.abs(arr[i]); 
        if(x - 1 < size && arr[x - 1] > 0) 
          arr[x - 1] = -arr[x - 1]; 
      } 
       
      // Return the first index value at which  
      // is positive 
      for(i = 0; i < size; i++) 
        if (arr[i] > 0) 
          return i+1;  // 1 is added becuase indexes  
                       // start from 0 
       
      return size+1; 
    } 
       
    /* Find the smallest positive missing  
       number in an array that contains 
       both positive and negative integers */
    static int findMissing(int arr[], int size) 
    { 
       // First separate positive and  
       // negative numbers 
       int shift = segregate (arr, size); 
       int arr2[] = new int[size-shift]; 
       int j=0; 
       for(int i=shift;i<size;i++) 
           { 
               arr2[j] = arr[i]; 
               j++; 
           }     
       // Shift the array and call  
       // findMissingPositive for 
       // positive part 
       return findMissingPositive(arr2, j); 
    } 
    // main function 
    public static void main (String[] args)  
    { 
        int arr[] = {0, 10,1,2, 2, -10, -20}; 
        int arr_size = arr.length; 
        int missing = findMissing(arr, arr_size); 
        System.out.println("The smallest positive missing number is "+  
                            missing); 
    } 
} 


Source-Geeksforgeeks

Question - Longest Common Substring in an Array of Strings

Input: grace graceful disgraceful gracefully
Output: grace

Input: sadness sad sadly
Output: sad

Solution - 

// Java program to find the stem of given list of 
// words 
import java.io.*; 
import java.util.*; 

class stem { 

// function to find the stem (longest common substring) from the string array 
public static String findstem(String arr[]) 
{ 
// Determine size of the array 
int n = arr.length; 

// Take first word from array as reference 
String s = arr[0]; 
int len = s.length(); 

String res = ""; 

for (int i = 0; i < len; i++) { 
for (int j = i + 1; j <= len; j++) { 

// generating all possible substrings 
// of our reference string arr[0] i.e s 
String stem = s.substring(i, j); 
int k = 1; 
for (k = 1; k < n; k++) 

// Check if the generated stem is 
// common to to all words 
if (!arr[k].contains(stem)) 
break; 
// If current substring is present in 
// all strings and its length is greater 
// than current result 
if (k == n && res.length() < stem.length()) 
res = stem; 
} 
} 
return res; 
} 

// Driver Code 
public static void main(String args[]) 
{ 
String arr[] = { "grace", "graceful", "disgraceful", "gracefully" }; 
String stems = findstem(arr); 
System.out.println(stems); 
} 
} 

Question - Given an amount convert the amount into different currencies - example- amount to us,indian,france,china and display.

Solution-

import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;

public class Solution {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double payment = scanner.nextDouble();
        scanner.close();

        /* Create custom Locale for India. 
          I used the "IANA Language Subtag Registry" to find India's country code */
        Locale indiaLocale = new Locale("en", "IN");

        NumberFormat us     = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat india  = NumberFormat.getCurrencyInstance(indiaLocale);
        NumberFormat china  = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

    
        System.out.println("US: "     + us.format(payment));
        System.out.println("India: "  + india.format(payment));
        System.out.println("China: "  + china.format(payment));
        System.out.println("France: " + france.format(payment));
    }
}

Question - Java Program to Print Diamond Pattern

Solution -

import java.util.*;
class dia
{
public static void main(String []args)
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int i=0,j=0;
int space=n-1;
for (j = 1; j <= n; j++) 
        {
            for (i = 1; i <= space; i++) 
            {
                System.out.print(" ");
            }
            space--;
            for (i = 1; i <= 2 * j - 1; i++) 
            {
                System.out.print("*");                
            }
            System.out.println("");
        }

        space = 1;
        
        for (j = 1; j <= n - 1; j++) 
        {
            for (i = 1; i <= space; i++) 
            {
                System.out.print(" ");
            }
            space++;
            for (i = 1; i <= 2 * (n - j) - 1; i++) 
            {
                System.out.print("*");
            }
            System.out.println("");
        }
}
}

Question  - Write a program to evaluate the postfix expression

input = a mathematical expression 
example = 231*+9-
output = -4

Solution

import java.util.Stack; 
  
class main 
{ 
    static int evaluatePostfix(String exp) 
    {  
        Stack<Integer> stack=new Stack<>(); 
           
        for(int i=0;i<exp.length();i++) 
        { 
            char c=exp.charAt(i); 
              
            if(Character.isDigit(c)) 
                stack.push(c - '0'); 
              
            else
            { 
                int val1 = stack.pop(); 
                int val2 = stack.pop(); 
                  
                switch(c) 
                { 
                    case '+': 
                    stack.push(val2+val1); 
                    break; 
                      
                    case '-': 
                    stack.push(val2- val1); 
                    break; 
                      
                    case '/': 
                    stack.push(val2/val1); 
                    break; 
                      
                    case '*': 
                    stack.push(val2*val1); 
                    break; 
              } 
            } 
        } 
        return stack.pop();     
     }
           
    public static void main(String[] args)  
    { 
        String exp="231*+9-"; 
        System.out.println("postfix evaluation: "+ evaluatePostfix(exp)); 
    } 
}

Question - Given a collection of intervals, merge all the overlapping intervals, for example-

given - [1,3] [2,6] [8,10] [15,18]
output- [1,6] [8,10] [15,18]

Solution-

import java.util.*;
class main
{
public static void main(String []args)
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int arr1[]=new int[n];
int arr2[]=new int[n];
int arr3[]=new int[n];
int arr4[]=new int[n];
int i,j,k=0;
int temp1=0,temp2=0;

for(i=0;i<n;i++)
{
arr1[i]=kb.nextInt();
arr2[i]=kb.nextInt();
}

for(j=0;j<n-1;j++)
{
if(arr2[j]>arr1[j+1])
{
System.out.println("Found at "+ arr1[j+1] +" and "+ arr2[j]);
temp1=j;
temp2=j+1;

}

}
       }
}

Question - Given an array of N elements, determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same.

input format- Input to contain a number of elements N, next line contain the N elements
5
3 1 5 9 12
Output format- Can be divided into two subsets of an equal sum

Solution-

import java.io.*; 
  
class main
{ 
    static boolean isSubsetSum (int arr[], int n, int sum) 
    { 

        if (sum == 0) 
            return true; 
        if (n == 0 && sum != 0) 
            return false; 
  

        if (arr[n-1] > sum) 
            return isSubsetSum (arr, n-1, sum); 
  

        return isSubsetSum (arr, n-1, sum) || 
               isSubsetSum (arr, n-1, sum-arr[n-1]); 
    } 
  

    static boolean findPartition (int arr[], int n) 
    { 

        int sum = 0; 
        for (int i = 0; i < n; i++) 
            sum += arr[i]; 
  

        if (sum%2 != 0) 
            return false; 
  

        return isSubsetSum (arr, n, sum/2); 
    } 
  
    public static void main (String[] args) 
    { 
  
        int arr[] = {3, 1, 5, 9, 12}; 
        int n = arr.length; 
        if (findPartition(arr, n) == true) 
            System.out.println("Can be divided into two "+ 
                                "subsets of equal sum"); 
        else
            System.out.println("Can not be divided into " + 
                                "two subsets of equal sum"); 
    } 
} 

__________________________________________________

source- geeksforgeeks.com

Question - You Are given an alphanumeric String. Write a program to find the sum of numbers in the given string.

input format-51b6de19
output format -21

Solution

import java.util.Scanner;
class main
{
public static void main(String [] args)
{
Scanner kb=new Scanner(System.in);
String word=kb.nextLine();
int length=word.length();
int sum=0;
for(int i=0;i<length;i++)
{
if(Character.isDigit(word.charAt(i)))
{
int temp=Character.getNumericValue(word.charAt(i));
sum=sum+temp;
}
}
System.out.println("The sum is" +sum);
}
}

Wednesday, 26 December 2018

CSE1007 - Wintersem 2018-19

Question- Slow learner problem
Write a program to demonstrate the knowledge of students in multidimensional arrays and looping
constructs.
Eg., If there are 4 batches in BTech - “CSE1007” course, read the count of the slow learners (who have scored <25) in each batch. Tutors should be assigned in the ratio of 1:4 (For every 4 slow learners, there should be one tutor). Determine the number of tutors for each batch. Create a 2-D jagged array with 4 rows to store the count of slow learners in the 4 batches. The number of columns in each row should be equal to the number of groups formed for that particular batch ( Eg., If there are 23 slow learners in a batch, then there should be 6 tutors and in the jagged array, the corresponding row should store 4, 4, 4, 4, 4,3). Use for-each loop to traverse the array and print the details. Also print the number of batches in which all tutors have exactly 4 students.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package practice.apps;

/**
 *
 * @author Naman Khurpia
 */
import java.util.Scanner;
public class faltu
{
    public static void main(String arr[])
    {
        Scanner b= new Scanner(System.in);
        int content,z;
        int ans=0;

        int a[][]=new int[4][];
        for(int i=0;i<4;i++)
        {
            System.out.println("Enter the number of slow learners in the batch "+i);
            content=b.nextInt();
            if(content%4==0)
                z=content/4;
            else
                z=content/4+1;
         
            a[i]=new int[z];

            for(int j=0;j<z;j++)
            {
                if(content>4)
                {
                    a[i][j]=4;
                    content=content-4;
                }
                else
                {
                    a[i][j]=content;
                    content=0;
                }
            }
        }
        System.out.println("\n\nThe Contents of Jagged array are");
        for(int i=0;i<4;i++)
        {
            for(int n:a[i])
            {
                System.out.print(n);
                if(n==4)
                    ans++;
            }
            System.out.println();
        }
        System.out.println("\n\nThe number of Tutors with 4 students are (ans) = "+ans);

    }

}




Question
Write a program to demonstrate the knowledge of students in String handling. Eg., Write a program to read a chemical equation and find out the count of the reactants and the products. Also display the count of the number of molecules of each reactant and product. Eg., For the equation, 2NaOH + H2SO4 -> Na2SO4+ 2H2O, the O/P should be as follows. Reactants are 2 moles of NaOH, 1 mole of H2SO4. Products are 1 mole of Na2SO4 and 2 moles of H2O.


Solution-
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package practice.apps;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;
/**
 *
 * @author Naman Khurpia
 */
class chemicals{
ArrayList<String> arrl1 = new ArrayList<String>(50); ArrayList<String> arrl2 = new
ArrayList<String>(50);
void add(String substring) {
throw new UnsupportedOperationException("Not supported yet."); //To change body ofgenerated methods, choose Tools | Templates.
}
}
public class moles {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String equation = scan.nextLine();
String reactants = " ";
String prod = " ";
for(int i=0;i<equation.length();i++){
if((equation.charAt(i)=='-') && (equation.charAt(i+1)=='>')){
reactants = equation.substring(0, i);
reactants = reactants.replaceAll("\\s","");
enter(reactants,"Reactants");
prod = equation.substring(i+2,equation.length());
prod = prod.replaceAll("\\s","");
enter(prod,"Product");
}
}
}
public static void enter(String s,String tpe){
chemicals total = new chemicals();
for(int i=0;i<s.length()-1;i++){
for(int j=i+1;j<s.length();j++){
if((s.charAt(j)=='+')){
String check=s.substring(i,j);
if(check.charAt(check.length()-1)=='+')
total.arrl1.add(check.substring(0,check.length()));
else
total.arrl1.add(check.substring(0,check.length()));
i=j+1;
}
else if((s.length()-1==j)){
String check2=s.substring(i,j+1);
if(check2.charAt(check2.length()-1)=='+')
total.arrl1.add(check2.substring(0,check2.length()));
else
total.arrl1.add(check2.substring(0,check2.length()));
i=j+1;
}
}
}
System.out.print( tpe+" are ");
for(int i=0;i<total.arrl1.size();i++){
Pattern p = Pattern.compile("^\\d*");
Matcher m = p.matcher(total.arrl1.get(i));
if (m.find()) {
if(!m.group().equals(""))
System.out.print(m.group(0)+" moles of"+total.arrl1.get(i).substring(m.group(0).length(),total.arrl1.get(i).length())+" ");
else
System.out.print("1 moles of "+total.arrl1.get(i)+" ");
}
}
System.out.println();
}
}



Screenshot-

Thursday, 5 July 2018

The Planet Food App

Here i will posting links for all UI (better and improved version of sir's)

SPLASH SCREEN-

here screen size is 700*350 px
and the image resource is of size 700*315 px 
35px for the progress bar


download the above image from 
LINK

CODE-
public class Splash_screen_frame extends javax.swing.JFrame {

 //declaring inner class object globally to be accessed by others
    SplashThread sp;
    
    public Splash_screen_frame() 
    {
        initComponents();
        super.setLocationRelativeTo(null);
        
        jProgressBar1.setStringPainted(true);
        sp=new SplashThread();
        sp.start();
    }


    //declaring new class
    class SplashThread extends Thread
    {
        public void run()
        {
            int count=1;
            Random r=new Random();
            while(jProgressBar1.getValue()<jProgressBar1.getMaximum())
            {
                try
                {
                    jProgressBar1.setValue((int)count);
                    Thread.sleep(1200);
                    count=count+r.nextInt(100);
                }
                catch(InterruptedException e)
                {
                    JOptionPane.showMessageDialog(null, "Exception in Thread"+e, "Error", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
            }
            Splash_screen_frame.this.dispose();
            Login_frame login=new Login_frame();
            login.setVisible(true);
        }
    }


}


DIRECTORY STRUCTURE-




LOGIN PAGE -

here screen size is 700*300 px
and the image resource is of size 350*300 px
350px for the login section which is placed over a panel



download the above image from 

CODE-
import Planet_Food.Dao.UserDao;
import Planet_Food.dbUtil.DBConnection;
import Planet_Food.pojo.User;
import Planet_Food.pojo.UserProfile;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class Login_frame extends javax.swing.JFrame {

    private String userId;
    private String password;
         
    public Login_frame()
    {
        initComponents();
        this.setLocationRelativeTo(null);
     
    }
 
    public boolean isvalidInput()
    {
        userId=txtUserId.getText();
        char []pwd=txtPassword.getPassword();
        if(userId.isEmpty() || pwd.length==0)
        {
            return false;
        }
        else
        {
            password=String.valueOf(pwd);//convert any type into string
            return true;
        }
     
    }
 
    private String getUserType()
    {
        if(jrAdmin.isSelected())
            return jrAdmin.getText();
        else if(jrCashier.isSelected())
            return jrCashier.getText();
        else
            return null;
    }

                                   

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                       
        //LOGIN here
     
        if(isvalidInput())
        {
            String usertype=null;
            if(usertype.equals(null))
            {
                JOptionPane.showMessageDialog(null, "Select a radio button","Error",JOptionPane.ERROR_MESSAGE);
            }
            else
            {
                //if all values are validated
                try
                {
                    User user=new User();
                    user.setUserId(userId);
                    user.setPassword(password);
                    user.setUserType(usertype);
                    String username=UserDao.validateUser(user);
                    if(username!=null)
                    {
                        //everything correct
                        JOptionPane.showMessageDialog(null, "Login Accepted","Wlcome"+username,JOptionPane.INFORMATION_MESSAGE);
                        UserProfile.setUsername(username);
                        UserProfile.setUsertype(usertype);
                        if(usertype.equalsIgnoreCase("admin"))
                        {
                            admin_option_frame adminFrame=new admin_option_frame();
                            adminFrame.setVisible(true);
                        }
                        else
                        {
                            Cashier_option_frame cashierFrame=new Cashier_option_frame();
                            cashierFrame.setVisible(true);
                        }
                        this.dispose();
                     
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "UserId or Password incorrect","Login Denied",JOptionPane.ERROR_MESSAGE);
                    }
                }
                catch(Exception e)
                {
                    JOptionPane.showMessageDialog(null, "DB error: "+e,"Exception",JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
             
            }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "UserId or Password incorrect","Incorrect",JOptionPane.ERROR_MESSAGE);
        }
     
    }                                     

    private void btnQuitActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        DBConnection.closeConnection();
        int ans=0;
            ans=JOptionPane.showConfirmDialog(null, "Are you sure?", "Quitting", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if(ans==JOptionPane.YES_OPTION)
            {
                System.exit(0);
            }
    }                                     

}

Now Create a package called PlanetFood.pojo

inside this create a java file named as User

CODE inside User-  (pojo)

public class User {
    
    private String userId;
    private String password;
    private String userType;

    public String getUserid() {
        return userId;
    }

    public void setUserId(String userid) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserType() {
        return userType;
    }

    public void setUserType(String userType) {
        this.userType = userType;
    }
    
}

Now create another class in pojo package named as  UserProfile

public class UserProfile {
    
    private static String username;
    private static String usertype;

    public static String getUsername() {
        return username;
    }

    public static void setUsername(String username) {
        UserProfile.username = username;
    }

    public static String getUsertype() {
        return usertype;
    }

    public static void setUsertype(String usertype) {
        UserProfile.usertype = usertype;
    }
    
}


Now Create a package called PlanetFood.dbUtils

inside this create a java class called DBConnection

Code-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class DBConnection {
   
    private static Connection conn=null;
   
    static
    {
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn=DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe","naman","naman");
            JOptionPane.showMessageDialog(null,"Successfully loaded","Sucess!",JOptionPane.INFORMATION_MESSAGE);
           
        }
        catch(ClassNotFoundException e)
        {
            JOptionPane.showMessageDialog(null,"class not found exception"+ e.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        catch (SQLException ex)
        {
            JOptionPane.showMessageDialog(null,"SQL Exception"+ ex.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
       
       
    }
    public static Connection getConnection()
        {
            return(conn);
        }
   
    public static void closeConnection()
    {
        if(conn!=null)
            {
                try{
                    conn.close();
       
                }
                catch(SQLException ex)
                {
                    JOptionPane.showMessageDialog(null,"Error while disconnecting","Exception",JOptionPane.ERROR_MESSAGE);
                   
                }
            }
    }
   
}


Now Create another package called FoodPlanet.Dao

inside this create a java class called UserDao

CODE-

import Planet_Food.dbUtil.DBConnection;
import Planet_Food.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Naman Khurpia
 */
public class UserDao {
   
    public static String validateUser(User user)throws SQLException
    {
        Connection conn=DBConnection.getConnection();
        String qry="select username from Users where userid=? and password=? and usertype=?";
        PreparedStatement ps=conn.prepareStatement(qry);
       
        ps.setString(1,user.getUserid());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getUserType());
        ResultSet rs=ps.executeQuery();
        String username=null;
        if(rs.next())//if we user while it will be the same as that of if,  no changes in that
        {
            username=rs.getString(1);
           
        }
        return  username;
    }
   
}





Tuesday, 3 July 2018

The EMP management app(with 5 functionality) 100% COMPLETE AND TESTED

DOWNLOAD THE ENTIRE WORKING PROJECT FROM HERE(netbeans project file)




DOWNLOAD

click on clone or download



OR follow yourself


Follow the steps carefully-


1. create a new netbeans project (name it as emp_management, or anything of your choice)
2. now create a package named as emp.gui (it is named as PROJECTNAME.PACKAGENAME).
3. now create a new JFrame Form and create the UI of the project.
4. before dragging the elements first place a PANEL in the frame and select colors then start placing the elements


5. Now create the following UI-

1 option frame- name it as option_frame


2 add employee frame name it as add_emp


3 search emp name it as search_emp


4 view all emp name it as view_all_emp



5. Now we will create a directory structure as following-


(Notice here how the package names are given packagename.source)
please make sure you name your package and java classes as mentioned
dao-data access objects
pojo-plain old java objects

6. create the required package and the required classes as shown in the diagram and create a table in SQL with the command-

create table emp_table(empno number(5),empname varchar2(20), salary number(10));

desc emp_table;

select * from emp_table;

7. now we will start off with pojo (most easiest)

contains the data elements getter and setters

CODE-

public class Emp {
    private int empno;
    private String ename;
    private double sal;

    public int getEmpno() {
        return empno;
    }

    public void setEmpno(int empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }
    
}


8. now we will open a JDBC connection- in dbuits.dbconnection

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class DBConnection {
    
    private static Connection conn=null;
    
    static
    {
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn=DriverManager.getConnection("jdbc:oracle:thin:@//pc-name:1521/xe","username","password");
            JOptionPane.showMessageDialog(null,"Successfully loaded","Sucess!",JOptionPane.INFORMATION_MESSAGE);
            
        }
        catch(ClassNotFoundException e)
        {
            JOptionPane.showMessageDialog(null,"class not found exception"+ e.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        catch (SQLException ex) 
        {
            JOptionPane.showMessageDialog(null,"SQL Exception"+ ex.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
        
        
    }
    public static Connection getConnection()//method will return us the connection object when we need it in other classes
        {
            return(conn);
        }
    
    public static void closeConnection()//method will close connection after use
    {
        if(conn!=null)
            {
                try{
                    conn.close();
        
                }
                catch(SQLException ex)
                {
                    JOptionPane.showMessageDialog(null,"Error while disconnecting","Exception",JOptionPane.ERROR_MESSAGE);
                    
                }
            }
    }

}


9. now we will code in EmpDao.java

import emp.dbuitl.DBConnection;
import emp.pojo.Emp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
//data access objects
public class EmpDao {

    //function for adding the employee
    public static boolean AddEmployee(Emp e)throws SQLException
    {
     
        Connection conn=DBConnection.getConnection();
        PreparedStatement ps=conn.prepareStatement("insert into emp_table values(?,?,?)");
     
        ps.setInt(1,e.getEmpno());
        ps.setString(2,e.getEname());
        ps.setDouble(3,e.getSal());
     
        int count=ps.executeUpdate();
        if(count==0)
        {
            return false;
        }
        else
        {
            return true;
        }
     

    }
 
//function for show all employees
    public static ArrayList<Emp> getAllEmp()throws SQLException
    {
        Connection conn=DBConnection.getConnection();
        ArrayList<Emp> empList=new ArrayList<>();
     
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select empno,empname,salary from emp_table");
     
        while(rs.next())
        {
         
            Emp e=new Emp();
         
            e.setEmpno(rs.getInt("empno"));       
            e.setEname(rs.getString("empname"));
            e.setSal(rs.getDouble("salary"));
         
            empList.add(e);
         
        }
        return empList;
    }
 
    //function for update employee
    public static boolean UpdateEmployee(Emp e) throws SQLException
    {
        Connection conn=DBConnection.getConnection();
        PreparedStatement ps=conn.prepareStatement("update emp_table set empname=? , salary=? where empno=?");
     
        ps.setString(1,e.getEname());
        ps.setDouble(2,e.getSal());
        ps.setInt(3,e.getEmpno());
                 
        int c=ps.executeUpdate();   
        return c != 0;//returns true if c is 1
     
    }
 
//function for delete employee
    public static boolean DeleteEmp(int enumber)throws SQLException
    {
        Connection conn=DBConnection.getConnection();
        PreparedStatement ps=conn.prepareStatement("Delete from emp_table where empno=?");
        ps.setInt(1,enumber);
        int c=ps.executeUpdate();
     
        return c!=0;
    }
 

//function to perform search
    public static Emp SearchEmp(int enumber)throws SQLException,NullPointerException
    {
        Emp e=null;
        Connection conn=DBConnection.getConnection();
        //PreparedStatement ps=conn.prepareStatement("select empname , salary,empno from emp_table where empno=?");
        //ps.setInt(1, enumber);
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select empname , salary,empno from emp_table where empno="+enumber);
     
     
     
        while(rs.next())
        {
            e=new Emp();
            e.setEname(rs.getString("empname"));
            e.setSal(rs.getDouble("salary"));
        }
     
        return e;
     
    }

}


10. now we will code in GUI-

Option frame-

CODE- //copy paste correctly i have removed initComponents(none of your business) from my code-

import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class optionFrame extends javax.swing.JFrame {


    public optionFrame() {
        initComponents();
        this.setLocationRelativeTo(this);
    }

    


    private void dotaskActionPerformed(java.awt.event.ActionEvent evt) {                                       
        
        if(jrbAddEmp.isSelected())
        {
            add_empoyee_frame add=new add_empoyee_frame();
            add.setVisible(true);
            this.dispose();
        }
        else if (jrbSearchEmp.isSelected())
        {
            Search_frame search=new Search_frame();
            search.setVisible(true);
            this.dispose();
        }
        else if(jrbShowAllEmp.isSelected())
        {
            Showall_frame show=new Showall_frame();
            show.setVisible(true);
            this.dispose();
        }
        else if(jrbUpdateEmp.isSelected())
        {
            UpdateEmp_frame update=new UpdateEmp_frame();
            update.setVisible(true);
            this.dispose();
        }
        else if(jrbDeleteEmp.isSelected())
        {
            DeleteEmp_frame delete=new DeleteEmp_frame();
            delete.setVisible(true);
            this.dispose();
        }
        else if(jrbQuit.isSelected())
        {
            int ans=0;
            ans=JOptionPane.showConfirmDialog(null, "Are you sure?", "Quitting", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if(ans==JOptionPane.YES_OPTION)
            {
                System.exit(0);
            }    
            
        }
        else
        {
            JOptionPane.showMessageDialog(null,"Please select an option","Error",JOptionPane.ERROR_MESSAGE);
        }
        
    }         


11. now we will code in  add employee-


CODE- (Copy paste correctly)

import emp.dao.EmpDao;
import emp.dbuitl.DBConnection;
import emp.pojo.Emp;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class add_empoyee_frame extends javax.swing.JFrame {

    public add_empoyee_frame() {
        initComponents();
        this.setLocationRelativeTo(this);
        //DBConnection.getConnection();
    }
    
                                   

    private void AddEmpActionPerformed(java.awt.event.ActionEvent evt) {                                       

        if(validateInput()==false)
        {
            JOptionPane.showMessageDialog(null,"Please enter all details","Input not entered",JOptionPane.ERROR_MESSAGE);
            return;
        }
        else
        {
            try
            {
                Emp e=new Emp();
                int empNo=Integer.parseInt(txtEmpNo.getText());
                String eName=txtEmpName.getText();
                double sal=Double.parseDouble(txtSal.getText());
                e.setEmpno(empNo);
                e.setEname(eName);
                e.setSal(sal);
                
                if(EmpDao.AddEmployee(e))//a method that returns true if all correct values inserted
                {
                    JOptionPane.showMessageDialog(null, "Record inserted Successfully","Success!",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Please enter correct values","Input incorrect",JOptionPane.ERROR_MESSAGE);
                }
                        
            }
            catch(SQLException e)
            {
                JOptionPane.showMessageDialog(null,"SQL Exception ","Exception",JOptionPane.ERROR_MESSAGE);
            }
        }
        
        
        
    }                                      

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //back button
        optionFrame option=new optionFrame();
        option.setVisible(true);
        this.dispose();
        
    }                                        

    

//create at end    
    private boolean validateInput()
    {
        if(txtEmpNo.getText().isEmpty() || txtEmpName.getText().isEmpty() || txtSal.getText().isEmpty())
        {
            return false;
        }
        else
        {
            return true;
        }

    }
    
                  
}


12. Now we will create a new page for view all employees

for that we will code in DAO (as it doesn't interact with the user)
and creation of the object is minimized.


CODE- for viewing all employee  we will code in GUI frame ShowAllEmp


import emp.dao.EmpDao;
import emp.pojo.Emp;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class Showall_frame extends javax.swing.JFrame {


    public Showall_frame() {
        initComponents();
        this.setLocationRelativeTo(this);
    }

                                     

    private void btnShowAllEmpActionPerformed(java.awt.event.ActionEvent evt) {                                              
        //show all recortds
        try {
           
            
                    ArrayList<Emp> empList=EmpDao.getAllEmp();
                    
                    if(empList.isEmpty())
                        {
                            JOptionPane.showMessageDialog(null,"This table has no records","Empty Table",JOptionPane.INFORMATION_MESSAGE);
                        }
                        else
                        {
                            String str=new String();
                            txtAllEmp.setText("");
                            str="EMPNO \t ENAME \t SALARY\n\n";
                            for(Emp e:empList)
                            {
                                str=str+e.getEmpno()+"\t"+e.getEname()+"\t"+e.getSal()+"\n";
                            }
                            txtAllEmp.setText(str);
                        }
            }
        catch(SQLException e)
        {
            JOptionPane.showMessageDialog(null,"SQLException here","Exception",JOptionPane.ERROR_MESSAGE);
        }

      
    }
              
}


13. For Update employees-

CODE-

import emp.dao.EmpDao;
import emp.pojo.Emp;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class Update_emp_frame extends javax.swing.JFrame {

    public Update_emp_frame() {
        
        initComponents();
        this.setLocationRelativeTo(this);
    }

   
    private void btnUpdateEmpActionPerformed(java.awt.event.ActionEvent evt) {                                             
//update butoon
        if(validateInput()==false)
        {
            JOptionPane.showMessageDialog(null,"Please enter Emp number to update details","Input not entered",JOptionPane.ERROR_MESSAGE);
            return;
        }
        else
        {
            try
            {
                Emp e=new Emp();
                int empNo=Integer.parseInt(txtEmpNo.getText());
                String eName=txtEmpName.getText();
                double sal=Double.parseDouble(txtSal.getText());
                
                e.setEmpno(empNo);
                e.setEname(eName);
                e.setSal(sal);
                
                if(EmpDao.UpdateEmployee(e))//a method that returns true if all correct values inserted
                {
                    JOptionPane.showMessageDialog(null, "Record updated Successfully","Success!",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Please enter correct values","Input incorrect",JOptionPane.ERROR_MESSAGE);
                }
            }
            catch(SQLException e)
            {
                JOptionPane.showMessageDialog(null,"SQL Exception here"+e.getMessage(),"Exception",JOptionPane.ERROR_MESSAGE);
            }
            catch(NumberFormatException e)
            {
                JOptionPane.showMessageDialog(null,"NumberFormat Exception ","Exception",JOptionPane.ERROR_MESSAGE);
            }
                
        }
        // TODO add your handling code here:
    }                                            

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        optionFrame option=new optionFrame();
        option.setVisible(true);
        this.dispose();
    }                                        


        
    //at the bottom
    
    private boolean validateInput()
    {
        if(txtEmpNo.getText().isEmpty())
        {
            return false;
        }
        else
        {
            return true;
        }

    }
            
}

14. To create delete frame

CODE-

import emp.dao.EmpDao;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class DeleteEmp_frame extends javax.swing.JFrame {

    public DeleteEmp_frame() {
        initComponents();
        this.setLocationRelativeTo(this);
    }

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          

    if(txtEmpNo.getText().isEmpty())
    {
        JOptionPane.showMessageDialog(null,"Please enter the emp no","Input not entered",JOptionPane.ERROR_MESSAGE);
    }
    else
    {
        try {
        int empno=Integer.parseInt(txtEmpNo.getText());
        
            if(EmpDao.DeleteEmp(empno))
            {
                JOptionPane.showMessageDialog(null, "Record Successfully Deleted","Success!",JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Record deosn't exist","Error!",JOptionPane.ERROR_MESSAGE);
            }
        } 
        catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, "SQL Exception","Exception",JOptionPane.ERROR_MESSAGE);
        }
    }
        
        
        
        
    }                                         

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        optionFrame option=new optionFrame();
        option.setVisible(true);
        this.dispose();
    }                                        


15. Now for Searching

CODE-

import emp.dao.EmpDao;
import emp.pojo.Emp;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Naman Khurpia
 */
public class Search_frame extends javax.swing.JFrame {


    public Search_frame() {
        
        initComponents();
        this.setLocationRelativeTo(this);
    }

                                               

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        
       //back
       
               optionFrame option=new optionFrame();
        option.setVisible(true);
        this.dispose();
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if(txtEmpNumber.getText().isEmpty())
        {
            JOptionPane.showMessageDialog(null,"Please enter emp name","Input not entered",JOptionPane.ERROR_MESSAGE);
        }
        else
        {
            try 
            {
                
                int e=Integer.parseInt(txtEmpNumber.getText());
                Emp emp=EmpDao.SearchEmp(e);
                if(emp==null)
                {
                    JOptionPane.showMessageDialog(null,"No Record Exist","Norecord",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                {
                txtEmpName.setText(emp.getEname());
                txtSalary.setText(Double.toString(emp.getSal()));//converting the received double into string by calling toString()
                }
            } 
            catch (SQLException ex) 
            {
                JOptionPane.showMessageDialog(null,"SQL Exception here","Exception",JOptionPane.ERROR_MESSAGE);
            }
        }
}
        
        


HOPE THE CODE IS COMPLETE !! Obviously it is.

HAPPY CODING !!

GPT4ALL - A new LLaMa (Large Language Model)

posted 29th March, 2023 - 11:50, GPT4ALL launched 1 hr ago  What if we use AI generated prompt and response to train another AI - Exactly th...