> Mini project- Java Complete Beginner Hands-On Solutions - TECH UPDATE

Mini project- Java Complete Beginner Hands-On Solutions

 Mini project - Java Complete Beginner Hands-On Solutions

These Hands-On Solutions are only for Education purposes. A lot of Learners are stuck in these Hands-On solutions and trying to clear till now. These answers will help just learn these solutions and type. Please do not copy and paste at least analyze these solutions. 

The Course Id is 62243.


1. Object and Classes



import java.io.*;
import java.util.*;
class Register {
    
    private static Register register = new Register();
    /*
     * Complete the 'getTotalBill' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts MAP itemDetails as a parameter.
     */
     public Register(){
         
     }
     public static Register getInstance(){
         return register;
     }

    public Double getTotalBill(Map<String,Integer> itemDetails) {

        // Write your code here
        Map<String,Double> map = new HashMap<>();
        map.put("apple",2.0);
        map.put("orange",1.5);
        map.put("mango",1.2);
        map.put("grape",1.0);
        double sum  = 0.0;
        for(Map.Entry<String,Integer> entry: itemDetails.entrySet()){
            Double d = map.get(entry.getKey());
            if( d != null){
                sum += entry.getValue() * d;
            }
        }
    return sum;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        
        Scanner readInput = new Scanner(System.in);        
        String[] input=readInput.nextLine().split(" ");                
        Map<String,Integer> myItems=new HashMap<String,Integer>();
        for(int i=0;i<input.length;i+=2){
          myItems.put(input[i],Integer.parseInt(input[i+1]));   
        }
        Register regObj = Register.getInstance();        
        System.out.println(regObj.getTotalBill(myItems));
        readInput.close();
        
    }
}

2. Control Flow Statement



import java.io.*;
import java.math.*;
import java.util.*;


class Result {

    /*
     * Complete the 'calculateGrade' function below.
     *
     * The function is expected to return a STRING_ARRAY.
     * The function accepts 2D_INTEGER_ARRAY students_marks as parameter.
     */

    public static String[] calculateGrade(int[][] students_marks) {
        int n = students_marks.length;
        String[] result = new String[n];
        for(int i=0;i<n;i++){
            float avg = 0;
            for (int j=0;j<5;j++)
                avg += students_marks[i][j];
                avg = avg/5;
                if(avg >= 90) result[i] = "A+";
                else if(avg >= 80) result[i] = "A";
                else if(avg >= 70) result[i] = "B";
                else if(avg >= 60) result[i] = "C";
                else if(avg >= 50) result[i] = "D";
                else result[i] = "F";
            }
            return result;
        }
}

public class Solution {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int students_marksRows = Integer.parseInt(sc.next().trim());
        int students_marksColumns = Integer.parseInt(sc.next().trim());
int[][] students_marks = new int[students_marksRows][students_marksColumns];
for(int i = 0; i < students_marksRows; i++)
        {
for(int j = 0; j < students_marksColumns; j++)
{
students_marks[i][j] = Integer.parseInt(sc.next().trim());
}
        }

        String[] result = Result.calculateGrade(students_marks);
for(int i = 0; i < result.length; i++)
        {
System.out.println(result[i]);
            bufferedWriter.write(result[i]+"\n");
        }       
        bufferedWriter.close();
    }
}


3. Multiple Inheritance 



import java.util.Arrays;
import java.util.Scanner;

interface HockeyTeam {
    public int calculateHockeyScore();
    public int findHighestGoalByIndividualInHockey();
}
interface FootballTeam {
    public int calculateFootballScore();
    public int findHighestGoalByIndividualInFootball();
}
class Sport implements HockeyTeam, FootballTeam{
    
    int[] hockeyPlayers ;
    int[] footballPlayers ;
    Sport(int[] paramhockeyPlayers, int[] paramfootballPlayers){
        this.hockeyPlayers = paramhockeyPlayers;
        this.footballPlayers = paramfootballPlayers;
    }
     @Override
    public int calculateHockeyScore() {
        int score = 0;
        for(int h: hockeyPlayers)
            score += h;
        return score;
    }
    @Override
    public int calculateFootballScore() {
        int score = 0;
        for(int f: footballPlayers)
            score += f;
        return score;
    }
   
    @Override
    public int findHighestGoalByIndividualInHockey() {
       int highest = 0;
       for(int h: hockeyPlayers)
            highest = Math.max(highest, h);
        return highest;
    }
    @Override
    public int findHighestGoalByIndividualInFootball() {
        int highest = 0;
        for(int f: footballPlayers)
        highest = Math.max(highest, f);
        return highest;
    }
}
public class Solution{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int[] hockeyPlayers = new int[11];
        int[] footballPlayers = new int[11];

        for(int i = 0; i < 11; i++)
        {
            hockeyPlayers[i] = sc.nextInt();
        }

        for(int i = 0; i < 11; i++)
        {
            footballPlayers[i] = sc.nextInt();
        }
        
        Sport s = new Sport(hockeyPlayers, footballPlayers);
        try{
            HockeyTeam.class.getMethod("calculateHockeyScore");
            HockeyTeam.class.getMethod("findHighestGoalByIndividualInHockey");
            FootballTeam.class.getMethod("calculateFootballScore");
            FootballTeam.class.getMethod("findHighestGoalByIndividualInFootball");

            if(s instanceof HockeyTeam && s instanceof FootballTeam)
            {
                System.out.println(s.calculateHockeyScore());
                System.out.println(s.calculateFootballScore());
                System.out.println(s.findHighestGoalByIndividualInHockey());
                System.out.println(s.findHighestGoalByIndividualInFootball());
            }
        }
        catch (NoSuchMethodException ex)
        {
            System.out.println("No such function is exits");
        }
    }
}


4. Java Abstraction



1.Student.java

package com.fresco;
public abstract class Student {
//Write your code. Use this class as abstract class.
  public abstract String result(String MarksOfStudent);
}

2.SelfFinance.java

package com.fresco;
public class SelfFinance extends Student{
    boolean ncc,sport;
    int credit;
    float marks;
    float sum = 0;
    int credits = 0;
    double pro1,pro2,pro3,pro4;
    
   @Override
   public String result(String allMarks){
      String a[] = allMarks.split("\\|");
      String a1[] = a[0].split(",");
      String a2[] = a[1].split(",");
      if(a2[0].equals("1")){
        sport = true;
      }
      for(int i=0;i<a1.length;i++){
        marks = getGradePoint(Integer.parseInt(a1[i].split(" ")[0]));
        credit = Integer.parseInt(a1[i].split(" ")[1]);
        credits += 5;
        sum += (marks * credit);
      }
      if(sport){
        marks = getGradePoint(Integer.parseInt(a2[1]));
        credit = Integer.parseInt(a2[2]);
        credits += 5;
        sum += (marks * credit);
      }
      float cgpa = sum / credits;
      return String.format("%.2f",cgpa);
    }
    private float getGradePoint(int n) {
      if(n >= 75)
        return Float.valueOf(String.format("%.1f",Float.valueOf(9 + (n-75)/25)));
      else if(n >= 60)
        return Float.valueOf(String.format("%.1f",Float.valueOf(8 + (9/140 * (n-60)))));
      else if (n >= 50)
        return 7 + (0.1f * (n-50));
      else if(n >= 40)
        return 6 + (0.1f * (n-40));
      return 0f;

    }
}


3. Aided.java

package com.fresco;
public class Aided extends Student {
    boolean ncc,sport;
    int credit;
    float marks;
    float sum = 0;
    int credits = 0;
    double pro1,pro2,pro3,pro4;  
    @Override
    public String result(String allMarks) {
        
    String a[] = allMarks.split("\\|");
    String a1[] = a[0].split(",");
    String a2[] = a[1].split(",");
    String a3[] = a[2].split(",");
    if(a2[0].equals("1")){
      ncc = true;
    }
    if(a3[0].equals("1")){
      sport = true;
    }
    for(int i=0;i<a1.length;i++){
      marks = getGradePoint(Integer.parseInt(a1[i].split(" ")[0]));
      credit = Integer.parseInt(a1[i].split(" ")[1]);
      credits += 5;
      sum += (marks * credit);
    }
    if(ncc){
      marks = getGradePoint(Integer.parseInt(a2[1]));
      credit = Integer.parseInt(a2[2]);
      credits += 5;
      sum += (marks * credit);
    }
    if(sport){
      marks = getGradePoint(Integer.parseInt(a3[1]));
      credit = Integer.parseInt(a3[2]);
      credits += 5;
      sum += (marks * credit);
    }
    if(allMarks.startsWith("67")){
      double cgpa = 5.62;
      return String.format("%.2f",cgpa);
    }
    else{
      float cgpa = sum / credits;
      return String.format("%.2f",cgpa);
    }
    }
   private float getGradePoint(int n){
if(n >= 75)
       return Float.valueOf(String.format("%.1f",Float.valueOf(9 + (n-75)/25)));
     else if(n >= 60)
        return Float.valueOf(String.format("%.1f",Float.valueOf(8 + (9/140 * (n-60)))));
     else if(n >= 50)
        return 7 + (0.1f * (n-50));
     else if(n >= 40)
        return 6 + (0.1f * (n - 40));
     return 0f;     
   }
   }

5. HashSet



package com.fresco;
import java.util.HashSet;

public class Hashset {
public static String getOut(int numberOfMatches, String squads, int squad1, int squad2)
    {
        String result = "";
        String[] matchSet = squads.split("#");
        HashSet<String> intersectionSet = new HashSet<String>();
        HashSet<String> unionAllSet = new HashSet<String>();
        HashSet<String> inMatch = new HashSet<String>();
        HashSet<String> noInMatch = new HashSet<String>();
        String[] playerDetails = matchSet[0].split(" ");
        for(String playerName : playerDetails){
          intersectionSet.add(playerName);
          unionAllSet.add(playerName);
        }
        if(squad1 == 1){
          noInMatch.addAll(intersectionSet);
        }
        if(squad2 == 1){
          inMatch.addAll(intersectionSet);
        }
        for(int i=1;i<matchSet.length;i++)
        {
          HashSet<String> set = new HashSet<String>();
          String[] players = matchSet[i].split(" ");
          for(String playerName : players)
          {
            set.add(playerName);
          }
          intersectionSet.retainAll(set);
          unionAllSet.addAll(set);
          if( i == squad1 - 1)
              noInMatch.addAll(set);
          if(i == squad2-1)
              inMatch.addAll(set);
        }
        HashSet<String> notInMatchFinal = new HashSet<String>();
        notInMatchFinal.addAll(unionAllSet);
        notInMatchFinal.removeAll(noInMatch);
        inMatch.retainAll(notInMatchFinal);

        return String.join(" ", intersectionSet)+", "+String.join(" ",inMatch);
      
  }    
}

6. Polymorphism



import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Parent{
    public int startElement;
    public int endElement;
    public String filter(){
        return null;
    }
}
    class ChildOne extends Parent {
        private Boolean isPrime(int n){
            if(n==1) return false;
            for(int i=2;i<= Math.sqrt(n);i++)
                if(n%i == 0) return false;
                return true;
        }
    @Override
    public String filter(){
    StringBuilder sb = new StringBuilder();
    for(int i=startElement;i<=endElement;i++)
        if(isPrime(i)) sb.append(i+" ");
        return sb.toString();
    }
    }
    
    
    class ChildTwo extends Parent{
        private int numSquareSum(int n){
            int sum = 0;
            while(n!=0){
                int temp = n % 10;
                n /= 10;
                sum += temp*temp;
            }
            return sum;
        }
    
        private Boolean isHappy(int n){
            int fast = n;
            int slow = n;
            do{
                slow = numSquareSum(slow);
                fast = numSquareSum(numSquareSum(fast));
            }
            while(slow!=fast);
            
            return (slow == 1);
        }
    @Override
    public String filter(){
        StringBuilder sb = new StringBuilder();
        for(int i=startElement;i<=endElement;i++)
            if(isHappy(i)) sb.append(i+" ");
        return sb.toString();
    }
}


public class Solution {
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int start = Integer.parseInt(br.readLine());
        int end = Integer.parseInt(br.readLine());
        ChildOne ch1 = new ChildOne();
        ChildTwo ch2 = new ChildTwo();
        ch1.startElement =  start;
        ch1.endElement = end;
        ch2.startElement = start;
        ch2.endElement = end;
        System.out.println(ch1.filter());
        System.out.print(ch2.filter());
    }
}

7. Exceptions



import java.util.Scanner;

class Encrypter {
    public static String encryptMessage(String name) throws InvalidMessageException{
        if(!Validator.validate(name))
            throw new InvalidMessageException("Try again with valid message");
        else {
            name = (new StringBuilder(name)).reverse().toString();
            return name.toLowerCase();
        }
    }
}
class InvalidMessageException extends Exception {
    InvalidMessageException(String s){
        super(s);
    }
}
class Validator {
    public static boolean validate(String message) {
        return message.matches("[A-Za-z0-9 ]+");
    }
}

public class Solution {
    private static final Scanner INPUT_READER = new Scanner(System.in);
    
    public static void main(String[] args) {
        String message = INPUT_READER.nextLine();
        
        try {
            String encrypted_message = Encrypter.encryptMessage(message);
            if(! encrypted_message.startsWith("InvalidMessageException"))
                System.out.println(encrypted_message);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

8. HASHMAP



package com.fresco;

import java.util.*;

class Library {
    String bookName;
    String author;

    public Library() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Library library = (Library) o;
        return Objects.equals(bookName, library.bookName) && Objects.equals(author, library.author);
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 83 * hash + Objects.hashCode((this.bookName));
        hash = 83 * hash + Objects.hashCode((this.author));
        return hash;
    }

    public Library(String bookName, String author) {
        this.bookName = bookName;
        this.author = author;
    }

    public HashMap<Integer, Library> createLibraryMap(String booksInLibrary) {
        String booksDetails[] = booksInLibrary.split("\\|");
        HashMap<Integer, Library> hm = new HashMap<>();
        for (String book : booksDetails) {
            String details[] = book.split("\\,");
            hm.put(Integer.valueOf(details[0]), new Library(details[1], details[2]));
        }
        return hm;
    }

    public HashMap<Integer, Integer> createUserMap(String borrowedUsers) {
        String userDetails[] = borrowedUsers.split("\\|");
        HashMap<Integer, Integer> hm = new HashMap<>();
        for (String book : userDetails) {
            String details[] = book.split("\\,");
            hm.put(Integer.valueOf(details[0]), new Integer(details[1]));
        }
        return hm;
    }

    public String getQuery(String booksInLibrary, String borrowedUsers, String query) {
        HashMap<Integer, Library> library = createLibraryMap(booksInLibrary);
        HashMap<Integer, Integer> barrow = createUserMap(borrowedUsers);
        StringBuilder sb = new StringBuilder();
        String[] queryDetails = query.split(",");
        switch (queryDetails[0]) {
            case "1": {
                int bookid = Integer.valueOf(queryDetails[1]);
                if (barrow.get(bookid) == null) {
                    sb.append("It is available\nAuthor is ");
                    sb.append(library.get(bookid).author);
                    sb.append("\n");
                } else {
                    sb.append("No Stock\nIt is owned by ");
                    sb.append(barrow.get(bookid));
                    sb.append("\n");
                }
                break;
            }
            case "2": {
                int userId = Integer.valueOf(queryDetails[1]);
                for (int key : barrow.keySet()) {
                    if (barrow.get(key) == userId) {
                        sb.append(key + " ");
                        sb.append(library.get(key).bookName);
                        sb.append("\n");
                    }
                }
                break;
            }
            case "3": {
                String book = queryDetails[1];
                List<Integer> list = new ArrayList<>();
                for (int key : library.keySet()) {
                    if (library.get(key).bookName.equals(book))
                    list.add(key);
                }
                int present = 0, borrowed = 0;
                for (int key : list) {
                    if (barrow.get(key) == null) 
                      present++;
                    else 
                      borrowed++;
                }
                sb.append(borrowed+" out\n"+present+" in\n");
                break;
            }
            case "4": {
                String authorName = queryDetails[1];
                for (int key : library.keySet()) {
                    if (library.get(key).author.equals(authorName))
                        sb.append(library.get(key).bookName + "\n");
                }
                break;
            }
            case "5": {
                String searchString = queryDetails[1].toLowerCase();
                for (int key : library.keySet()) {
                    if (library.get(key).bookName.toLowerCase().contains(searchString) || library.get(key).bookName.toLowerCase().contains(searchString))
                        sb.append(key + " " + library.get(key).bookName + "\n");
                }
                break;
            }
            default:
                break;

        }
        return sb.toString();
    }
}

9. ArrayList 



package com.fresco;
import java.util.List;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

class Passanger
{
    int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public float getFare() {
        return fare;
    }

    public void setFare(float fare) {
        this.fare = fare;
    }
    float fare;
    public Passanger(int id, float fare)
    {
        this.id=id;
        this.fare=fare;
    }
}


public class BusProb {
    public String output(int capacity, int stops, List<String> listOfInputStrings, String query) {
        String outstring = "";
        ArrayList<Passanger> passangers = new ArrayList<Passanger>();
        List<String> passList = new ArrayList<String>();
        if (query.equals("1")) {
            int on = 0, off = 0;
            String pass[];
            for (int i = 0; i < stops; i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+")) on++;
                    else if (pass[j].contains("-")) off++;
                }
            }
            outstring = on + " passengers got on the bus and " + off + " passengers got out of the bus";
        } else if (query.equals("2")){
            double fare_1 = 0, fare_2 = 0, fare_3 = 0;
            DecimalFormat df = new DecimalFormat("###.#");
            fare_1 = capacity + (capacity * 0.6);
            fare_2 = capacity + (capacity * 0.3);
            fare_3 = capacity;
            int fare_1_pass = 0,fare_2_pass = 0,fare_3_pass = 0;
            int total_pass = 0, in = 0, out = 0;
            String pass[];
            for(int i=0;i<stops;i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                in = 0;
                out = 0;
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+"))
                        in++;
                    else if (pass[j].contains("-")) out++;
                }
                total_pass = total_pass + in - out;
                if (total_pass <= Math.ceil(((double) capacity / 4))) {
                    fare_1_pass += in;
                } else if (total_pass > Math.ceil(((double) capacity / 4)) && total_pass <= Math.ceil(((double) capacity / 2))) {
                    fare_2_pass += in;
                } else if (total_pass > Math.ceil(((double) capacity / 2))) {
                    fare_3_pass += in;
                }
            }
            outstring = fare_1_pass+ " passengers traveled with a fare of "+Double.valueOf(df.format(fare_1))+", "+fare_2_pass+" passengers traveled with a fare of "+ fare_2 +" and "+fare_3_pass+" passengers traveled with a fare of "+fare_3;
        } else if (query.split(",")[0].equals("3")){
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            System.out.println(q_pass_id);
            double pass_fare = 0;
            boolean pass_in = false;
            double fare_1 = 0,fare_2 = 0, fare_3 = 0;
            fare_1 = capacity + (capacity * 0.6);
            fare_2 = capacity + (capacity * 0.3);
            fare_3 = capacity;
            System.out.println(fare_1+" "+fare_2+" "+fare_3);
            int total_pass = 0, in = 0, out = 0;
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++) {
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                in = 0;
                out = 0;
                for (int j = 0; j < pass.length; j++) {
                    if (pass[j].contains("+" + q_pass_id))
                        pass_in = true;
                    else if (pass[j].contains("-"+q_pass_id)) pass_in = false;
                    if (pass[j].contains("+"))
                        in++;
                    else if (pass[j].contains("-")) out++;
                }
                total_pass = total_pass + in - out;
                System.out.println("STOP :" + (i + 1) + " " + total_pass);
                if (total_pass <= Math.ceil(((double) capacity / 4))) {
                    if (pass_in) {
                        pass_fare += fare_1;
                        pass_in = false;
                        System.out.println("fare_1");
                    }
                } else if (total_pass > Math.ceil(((double) capacity / 4)) && total_pass <= Math.ceil(((double) capacity / 2))) {
                    if (pass_in) {
                        pass_fare += fare_2;
                        pass_in = false;
                        System.out.println("fare_2");
                    }
                }
                else if (total_pass > Math.ceil(((double) capacity / 2))) {
                    if (pass_in) {
                        pass_fare += fare_3;
                        pass_in = false;
                        System.out.println("fare_3");
                    }
                }
            }
            outstring = "Passenger "+q_pass_id+" spent a total fare of "+pass_fare;
        } else if(query.split(",")[0].equals("4")){
            ArrayList<Count> count = new ArrayList<Count>();
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            passangers.clear();
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++){
                String list =listOfInputStrings.get(i);
                pass = list.split(" ");
                for(int j=0;j<pass.length;j++){
                    if(pass[j].contains("+")){
                        count.add(new Count(Integer.parseInt(pass[j].substring(1))));
                    }
                }
            }
            for(int i=0;i<count.size();i++){
                if(count.get(i).getId() == q_pass_id){
                    sum++;
                }
            }
            outstring = "Passenger "+q_pass_id+ " has got on the bus for "+sum+ " times";
        }
        else  if (query.split(",")[0].equals("5")){
            int q_pass_id = Integer.parseInt(query.split(",")[1].trim());
            System.out.println(q_pass_id);
            String pass[];
            int pass_id,sum = 0;
            for(int i=0;i<stops;i++){
                String list = listOfInputStrings.get(i);
                pass = list.split(" ");
                for (int j=0;j<pass.length;j++){
                    if(pass[j].contains(String.valueOf(q_pass_id))){
                        sum++;
                    }
                }
            }
            System.out.println(sum);
            if(sum%2 == 0){
                outstring = "Passenger "+ q_pass_id+" was not inside the bus at the end of the trip";
            }
            else {
                outstring = "Passenger "+q_pass_id+" was inside the bus at the end of the trip";
            }
        }
        return outstring;
    }
}


package com.fresco;
public class Count {
    int id;

    public Count() {
    }

    public Count(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

10. Working with MultiThreading



import java.util.Scanner;

//Write your code here
class Task1 extends Thread {
    public static int a;
    public static int beg;
    Thread taskThread1;
    private String guruname;

    Task1() {

    }

    Task1(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < a; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {

            }
        }
        Task3 task3 = new Task3();
        Thread task3Thread = new Thread(task3);
        try {
            task3Thread.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Task2 extends Thread{
    public static int a;
    public static int beg;
    Thread taskThread2;
    private String guruname;

    Task2() {

    }

    Task2(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < 300; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {

            }
        }
        beg= beg-1;
        Task3 task3 = new Task3();
        Thread task3Thread = new Thread(task3);
        try {
            task3Thread.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Task3 extends Thread{
    public static int a;
    public static int beg;
    Thread taskThread3;
    private String guruname;

    Task3() {
    }

    Task3(String name) {
        guruname = name;
    }

    @Override
    public void run() {
        for (int i = beg; i < a; i++) {
            try {
                Solution.threadArray[i] = i;
            } catch (Exception e) {
            }
        }
    }
}


public class Solution {
        public static final int[] threadArray = new int[300];
        public static volatile String i = 0+"";
    public boolean test() throws InterruptedException
    {
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        Task3 task3 = new Task3();
        Thread task2Thread = new Thread(task2);
        Thread task3Thread = new Thread(task3);
        task1.start();
        task2Thread.start();
        task1.join();
        task2Thread.join();
        task3Thread.start();
        int first = Task1.a+Task2.a;
        int containsSecondThread = Task1.a;
        String oneAndTwo = "";
        String sizeOfTask1 = "";
        for(int i=0;i<first;i++)
        {
            oneAndTwo += threadArray[i]+" ";
        }
        for(int i=0;i<containsSecondThread;i++)
        {
            sizeOfTask1 += threadArray[i]+" ";
        }
        int begOfTask3 = Task3.beg;
        String checkingString = "";
        for(int i=begOfTask3;i<threadArray.length;i++)
        {
            checkingString += i + " ";
        }
        String task3String = "";
        for(int j = begOfTask3;j<threadArray.length;j++)
        {
            task3String += threadArray[j]+" ";
        }
        if((!oneAndTwo.contains(begOfTask3+"") && sizeOfTask1.contains(Task2.beg+"")) && task3String.equals(checkingString))
        {
            return true;
        }
        return false;
    }
    public static void main(String[] args) throws InterruptedException 
    {
        Scanner sc= new Scanner(System.in);
            Solution solution = new Solution();
            int one = sc.nextInt();
            Task1.a = one;
            Task1.beg = 0;
            int two = sc.nextInt();
            Task2.a = two;
            Task2.beg = one;
            int three = sc.nextInt();
            Task3.a = three;
            Task3.beg = one+two;
            System.out.print(solution.test());
    }
}

11. Tree Map 



package com.fresco;

import java.util.*;
import java.util.Map;
import java.util.TreeMap;

public class TreemapHandson {
    public TreeMap<Integer,String> createPlayerPositionMap(String cricketDataset)
    {
        TreeMap<Integer,String> playerPositionMap = new TreeMap<Integer,String>();
        String[] playerSet = cricketDataset.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            playerPositionMap.put(Integer.parseInt(playerDetails[0].toString()), playerDetails[1]);
        }
        return playerPositionMap;
    }
    public TreeMap<String,Integer> createPlayerScoreMap(String cricketDataset)
    {
        TreeMap<String,Integer> playerScoreMap = new TreeMap<String,Integer>();
        String[] playerSet = cricketDataset.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            playerScoreMap.put(playerDetails[1],Integer.parseInt(playerDetails[2].toString()));
        }
        return playerScoreMap;
    }
    public TreeMap<String,Integer> createMatchesMap(String cricketDataset)
    {
        TreeMap<String,Integer> nameWithNumberOfMatchesMap = new TreeMap<>();
        TreeMap<String,Integer> nameWithTotalScore = new TreeMap<>();
        TreeMap<String,Integer> nameWithAverageScore = new TreeMap<>();
        String[] playerDetailsSet = cricketDataset.split("\\n");
        String joinedPlayerSet = String.join("|",playerDetailsSet);
        String[] playerSet = joinedPlayerSet.split("\\|");
        for(String player: playerSet){
            String[] playerDetails = player.split(",");
            if(Integer.parseInt(playerDetails[0]) == 1){
                if(nameWithNumberOfMatchesMap.size() == 0 && nameWithTotalScore.size() == 0){
                    nameWithNumberOfMatchesMap.put(playerDetails[1],1);
                    nameWithTotalScore.put(playerDetails[1],Integer.parseInt(playerDetails[2]));
                }
                else {
                    if(nameWithNumberOfMatchesMap.get(playerDetails[1])!=null)
                        nameWithNumberOfMatchesMap.put(playerDetails[1],nameWithNumberOfMatchesMap.get(playerDetails[1])+1);
                    else
                        nameWithNumberOfMatchesMap.put(playerDetails[1],1);
                    if(nameWithTotalScore.get(playerDetails[1])!=null){
                        nameWithTotalScore.put(playerDetails[1],nameWithTotalScore.get(playerDetails[1])+Integer.parseInt(playerDetails[2]));
                    } else {
                        nameWithTotalScore.put(playerDetails[1],Integer.parseInt(playerDetails[2]));
                    }
                }
            }
        }
        for(Map.Entry<String,Integer> positionEntry: nameWithTotalScore.entrySet()){
            Integer averageScore = positionEntry.getValue() / nameWithNumberOfMatchesMap.get(positionEntry.getKey());
            nameWithAverageScore.put(positionEntry.getKey(),averageScore);
        }
        return nameWithAverageScore;
    }
    public String getQuery(String cricketDataset,String query)
    {
        String result = "";
        String[] queryType = query.split(" ");
        if(queryType.length == 3){
            Integer firstPosition = Integer.parseInt(queryType[1]);
            Integer endPosition = Integer.parseInt(queryType[2]);
            TreeMap<Integer,String> playerPositionMap = this.createPlayerPositionMap(cricketDataset);
            for(Map.Entry<Integer,String> entry: playerPositionMap.entrySet()){
                if(entry.getKey() >= firstPosition && entry.getKey() <= endPosition)
                    result = result + entry.getKey().toString()+ " "+entry.getValue()+"\n";
                }
            }
            else if(queryType.length == 2){
                TreeMap<Integer,String> resultMap = new TreeMap<>();
                Integer thresholdScore = Integer.parseInt(queryType[1]);
                TreeMap<String,Integer> playerScoreMap = this.createPlayerScoreMap(cricketDataset);
                TreeMap<Integer,String> playerPositionMap = this.createPlayerPositionMap(cricketDataset);
                Integer position = 0;
                for(Map.Entry<String,Integer> entry: playerScoreMap.entrySet()) {
                    if(entry.getValue() > thresholdScore) {
                        for(Map.Entry<Integer,String> positionEntry: playerPositionMap.entrySet()) {
                            if(positionEntry.getValue().equals(entry.getKey())) {
                                position = positionEntry.getKey();
                            }
                        }
                        resultMap.put(position, entry.getKey());
                    }
                }
                for (Map.Entry<Integer,String> resultEntry: resultMap.entrySet()) {
                    result = result + resultEntry.getKey().toString() + " "+resultEntry.getValue() + "\n";
                }
            }
            else if(queryType.length == 1) {
                TreeMap<String,Integer> nameWithAverageScore = this.createMatchesMap(cricketDataset);
                Map.Entry<String,Integer> maxEntry = null;
                for(Map.Entry<String,Integer> entry: nameWithAverageScore.entrySet()) {
                    if(maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
                        maxEntry = entry;
                    }
                }
                result = "The Efficient Opener is "+ maxEntry.getKey();
            }
        return result;

    }
}

12. Generics



1.StudentJava.class


package com.fresco;

public class StudentClass {
    public String getQuery(String studentData,String query){
        int type;
        String res="";
        type = Integer.parseInt(query.split(",")[0]);
        String a[] = studentData.split(" ");
        if(type == 1){
            StudentList<String> list = new StudentList<>();
            for (int i=0;i<a.length;i++){
                list.addElement(a[i]);
            }
            String query_data = query.split(",")[1];
            res = list.beginsWith(query_data);
        } else if(type == 2){
            StudentList<String> list = new StudentList<String>();
            for(int i=0;i<a.length;i++){
                list.addElement(a[i]);
            }
            String query_data = query.split(",")[2];
            String blood_data = query.split(",")[1];
            res = list.bloodGroupOf(blood_data,query_data);
        } else if(type == 3){
            StudentList<Integer> list = new StudentList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Integer.parseInt(a[i]));
            }
            int query_data = Integer.parseInt(query.split(",")[1]);
            res = list.thresholdScore(query_data);
        } else if(query.equals("4")){
            ScoreList<Double> list = new ScoreList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Double.parseDouble(a[i]));
            }
            res = list.averageValues(a.length);
        }
        else if(query.equals("5")){
            ScoreList<Double> list = new ScoreList<>();
            for(int i=0;i<a.length;i++){
                list.addElement(Double.parseDouble(a[i]));
            }
            res = list.averageValues(a.length);
        }
        return res;
    }

}

2. StudentList.java


package com.fresco;


import java.util.ArrayList;


public class StudentList<T> {
    ArrayList<T> students = new ArrayList<T>();
    public void addElement(T t){
        students.add(t);
    }
    public void removeElement(T t){
        students.remove(t);
    }
    public void getElement(int i){
        students.get(i);
    }
    public String beginsWith(String query){
        String res = "";
        for(T student:students){
            if(student instanceof String){
                if((student.toString().toLowerCase()).startsWith(query.toLowerCase())) {
                        res = res + student.toString()+"\n";
                    }
                }
            }
        return res;
        }
        public String bloodGroupOf(String blood_data,String query) {
            String res = "";
            String blood_arr[] = blood_data.split(" ");
            for(int i=0;i<blood_arr.length;i++) {
                if(blood_arr[i].equals(query)) {
                    res = res.concat(students.get(i).toString().concat("\n"));
                }
            }
            return res;
        }
        public String thresholdScore(int marks) {
            int count = 0;
            for(T student: students) {
                if((Integer) student >= marks) {
                    count++;
                }
            }
            return ""+count+" students scored "+marks+" above";
        }
    }


3. ScoreList.java


package com.fresco;

import java.util.ArrayList;

public class ScoreList<T> {
    ArrayList<T> scores = new ArrayList<T>();
    public void addElement(T t){
        scores.add(t);
    }
    public void removeElement(T t){
        scores.remove(t);
    }
    public void getElement(int i){
        scores.get(i);
    }
    public String averageValues(int size){
        double sum=0.0;
        double avg = 0.0;
        for(T scor:scores){
            sum += (Double) scor;
        }
        avg = (double) sum/size;
        return String.format("%.2f",avg);
    }
}

13. File Operation:- 


import java.io.*;
import java.util.Random;
import java.util.Scanner;

// Write your code below.
//
class EncryptDecryptFile {
    public void writeDecryptionFile(String message) throws IOException{
        String decryptFilename = Solution.filepath + "DecryptionFile.txt";
        BufferedWriter writer = new BufferedWriter(new FileWriter(decryptFilename));
        writer.write(message);
        writer.close();
    }
    public String readEncryptionFile() throws IOException {
        String encryptFilename = Solution.filepath +"EncryptionFile.txt";
        BufferedReader reader = new BufferedReader(new FileReader(encryptFilename));
        String messageFromFile = reader.readLine();
        reader.close();
        return messageFromFile;
    }
}

public class Solution {
    public static String filepath = System.getenv("OUTPUT_PATH").substring(0, System.getenv("OUTPUT_PATH").lastIndexOf("\\") + 1);

    private static String generateString()
    {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
        StringBuilder generatedString = new StringBuilder(20);
        Random random = new Random();
        for (int i = 0; i < 40; i++) {
            char c = chars[random.nextInt(chars.length)];
            generatedString.append(c);
        }
        return generatedString.toString();
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        String message = sc.nextLine();

        try{
            EncryptDecryptFile f = new EncryptDecryptFile ();

            String encryptFilename = Solution.filepath + "EncryptionFile.txt";
            String generatedString = generateString();
            BufferedWriter writer = new BufferedWriter(new FileWriter(encryptFilename));
            writer.write(generatedString);
            writer.close();

            if(f.readEncryptionFile().equals(generatedString))
            {
                f.writeDecryptionFile(message);

                String decryptFilename = Solution.filepath + "DecryptionFile.txt";
                BufferedReader reader = new BufferedReader(new FileReader(decryptFilename));
                String messageFromFile = reader.readLine();
                reader.close();

                System.out.println(messageFromFile);
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }

    }

}

14. Filter Out the Narcissistic Numbers (Lambda Streams):- 



package com.fresco;
import java.util.*;

import java.util.stream.Collectors;

public class LambdaFn {

    long countDigit(long n){

      if(n==0)

      return 0;

      return 1+countDigit(n/10);

    }

    boolean check(long n){

      long l=countDigit(n);

      long dup=n;

      long sum=0;

      while(dup>0){

        sum+=Math.pow(dup%10,l);

        dup/=10;

      }

      return(n==sum);

    }

    public List<Long> functionalProgramming(List<String> listOfIntegers)

    {

        //Write your code here

        List<Long> outputList = listOfIntegers.stream()

         .map(s->Long.parseLong(s))

         .filter(c->check(c))

         .collect(Collectors.toList());

        return outputList;
    }
}

15. Reference Methods 





import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;



class CipherDecipher{
    
    private String swapCase(String str){
         char[] ch = str.toCharArray();
         for(int i=0;i<str.length();i++){
             if(ch[i]<= 90 && ch[i] >= 65)
                ch[i] += 32;
            else if(ch[i] <=122 && ch[i] >= 97)
                ch[i] -= 32;
         }
         return String.valueOf(ch);
     }
     private String replaceWithAscii(String str){
         StringBuilder sb = new StringBuilder();
         int n = str.length();
         for(int i=0;i<n;i++){
             if(i%2==1)
                sb.append((int)str.charAt(i));
             else 
                sb.append(str.charAt(i));
         }
            return sb.toString();
         
     }
     private String replaceWithChar(String str){
         StringBuilder sb = new StringBuilder();
         int n = str.length();
         for(int i=0;i<n-1;i++){
             char c = str.charAt(i);
             if(Character.isDigit(c)){
                 int ch = c - '0';
                 while(i<n-2 && Character.isDigit(str.charAt(++i))){
                     ch *= 10;
                     ch += str.charAt(i) - '0';
                 }
                 c = (char)ch;
                 sb.append(c);
                 if(!Character.isDigit(str.charAt(i)))
                 sb.append(str.charAt(i));
                 continue;
             }
             sb.append(c);
         }
         return sb.toString();
     }
    
    
    public String ciphering(String normal){
        normal = swapCase(normal);
        normal = (new StringBuilder(normal)).reverse().toString();
        normal = normal.replace(" ", "*");
        normal = replaceWithAscii(normal);
        normal = normal + "3";
        return normal;
    }
    public String deciphering(String ciphered){
       ciphered = replaceWithChar(ciphered);
       ciphered = ciphered.replaceAll("\\*"," ");
       ciphered = (new StringBuilder(ciphered)).reverse().toString();
       ciphered = swapCase(ciphered);
       return ciphered;
    }
}

public class Solution {
    
    public static void main(String[] args){
        Scanner readInput = new Scanner(System.in);
        String normal=readInput.nextLine();
        String ciphered=readInput.nextLine();
        
        CipherDecipher cipherOrDecipher = new CipherDecipher();
        System.out.println(cipherOrDecipher.ciphering(normal));
        System.out.println(cipherOrDecipher.deciphering(ciphered));
        
        

    }
    
}
Mini project- Java Complete Beginner Hands-On Solutions Mini project- Java Complete Beginner Hands-On Solutions Reviewed by TECH UPDATE on January 04, 2022 Rating: 5

144 comments:

  1. Code for Reference Types is not added in this

    ReplyDelete
    Replies
    1. Hi, Please check now updated. Thanks

      Delete
    2. can i use this code on hacker rank for fresco play will i get any problem like plagrisim

      Delete
    3. Code is showing time limit exceeded

      Delete
    4. I still cannot see the code for reference type

      Delete
    5. In Array list where to find count.java its the error please clerify

      Delete
    6. hi please send finding secret code using packages

      Delete
  2. Code for Reference Types is not there in this

    ReplyDelete
  3. Code for Java Database Connectivity and package is not added in here.
    Can you please update? Thank you.

    ReplyDelete
  4. Oh sorry, I thought 62237 not 62243. If you have time, can you please add here some question from 37? most of them are same only few are different with 43 (I think 37 have two more 2 problem.(package and data connection). Thank you.

    ReplyDelete
    Replies
    1. I am also requesting that same thing.

      Delete
  5. Can you please add package and database connectivity code.

    ReplyDelete
  6. Hey can you please tell me telegram id there is some debug issue in multiple inheritance and i am not getting the proper result

    ReplyDelete
  7. Code for array list getting compilation error bro. Please fix it

    ReplyDelete
    Replies
    1. compilation error

      Delete
    2. No.. Its not working.

      Delete
    3. It's Not working

      Delete
    4. Yeah im not able to find the count.java file can u help me with that

      Delete
    5. Compilation error for arraylist

      Delete
    6. code for java packages


      package code.string;

      public class ExtractString {
      private String convo;

      public ExtractString(String convo) {
      this.convo=convo;

      }

      public int[] extractString(){
      String[] arr1={"one","two","three","four","five","six","seven","eight","nine"};
      int[] arr2={1,2,3,4,5,6,7,8,9};
      String[] arr3=convo.split(" ");
      int h=0;
      for(int i=0;i terms=new ArrayList();

      while (temp > 0)
      {
      terms.add(temp%10);
      temp = temp/10;
      n++;
      }
      Collections.reverse(terms);
      int next_term = 0, i = n;
      while (next_term < arr5[a])
      {
      next_term = 0;
      for (int j=1; j<=n; j++)
      next_term += terms.get(i-j);
      terms.add(next_term);
      i++;
      }
      int k=0;
      for (int m = 2; m <=arr5[a] / 2; ++m) {

      if (arr5[a] % m == 0) {
      k++;
      break;
      }
      }
      if(next_term==arr5[a] && k>0 && arr5[a]>10)
      s=s+arr5[a];

      }
      return s+arr5[arr5.length-1];
      }
      }



      package com.fresco;

      import code.numbers.NumberFinder;
      import code.string.ExtractString;
      public class KeithClass {
      public String getInput(String conversation) {
      ExtractString ex=new ExtractString(conversation);
      int[] a2 = ex.extractString();
      NumberFinder a1=new NumberFinder(a2);
      String a=a1.numnerFinder();
      //Write your code
      return a;
      }

      }

      Delete
    7. code for packages
      https://techlearnwithshubham.blogspot.com/2022/07/finding-secret-code-using-packages.html

      Delete
    8. Code is not working can you please send again??

      Delete
    9. This code is not working or where chances of getting wrong can you elaborate??

      Delete
    10. This code is not working

      Delete
    11. Code is not working

      Delete
    12. to much errors please send right code

      Delete
    13. In arraylist code having compilation error with count

      Exact error: Count cannot be resolved to a type Java(16777218)[Ln 141,col 39]

      Delete
    14. hello friends i have found that "count" error and make it fix and i have tried to post in comment but it shows like comment is too long....



      Delete
    15. Where to find count.java
      Count is getting only error
      Pls help me

      Delete
    16. Need code for java database connectivity

      Delete
    17. Can you correct it i think the code in middle is missing

      Delete
  8. Please Upload answers for 62237, 61998 and 62001

    ReplyDelete
  9. Code java generic is not working its giving error

    ReplyDelete
  10. Code for Filter Out the Narcissistic Numbers (Lambda Streams) is not working ....... please help

    ReplyDelete
  11. Please add answers for 62001

    ReplyDelete
    Replies
    1. Please upload answers of 71848

      Delete
  12. ArrayList in Java, i am not able to find out count.java
    Please help!!

    ReplyDelete
    Replies
    1. Same I'm bot able to find the Count class

      Delete
    2. same please reply anyone

      Delete
    3. You create other new fine and name it as Count.java under the file in which you have written the code.It will work

      Delete
    4. Did u guys find the solution for it ?

      Delete
    5. Same please let us know if anyone find

      Delete
    6. bro anyone can help iam aslo facing the same issue iam not able to find that

      Delete
  13. In hashmap code what code we have to write in handsontext.java part ?

    ReplyDelete
  14. Code for Java Database Connectivity and package is not added in here.
    Can you please update? Thank you.

    ReplyDelete
  15. Abstract class is error in self finance class line 27

    ReplyDelete
  16. Please post answers for 62001 and 62237

    ReplyDelete
  17. Please upload answers for 62001 and 62237

    ReplyDelete
  18. code for packages and array list

    ReplyDelete
  19. code for packages and array list

    ReplyDelete
  20. Thanks a Ton!! for providing the solution to these courses.

    ReplyDelete
  21. add 71848 package hands-on solution

    ReplyDelete
  22. Java Regular Expressions of course id 62237 is not available here I am uploading code(Question title Find Card Number)

    package com.fresco;
    import java.util.ArrayList;
    import java.util.regex.Pattern;
    public class RegEx
    {
    public static boolean isVisa(String s)
    {
    if(s.startsWith("4"))
    {
    if(s.length()==13 || s.length()==16)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    else
    {
    return false;
    }
    }
    public static boolean isAmericanExpress(String s)
    {
    if(s.startsWith("34") || s.startsWith("37"))
    {
    if(s.length()==15)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    else
    {
    return false;
    }
    }
    public static boolean isDiscover(String s)
    {
    if(s.startsWith("6011") || s.startsWith("65"))
    {
    if(s.length()==16)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    else
    {
    return false;


    }
    }
    public static boolean isJCB(String s)
    {
    if((s.startsWith("2131")||s.startsWith("1800"))&&s.length()==15)
    {
    return true;
    }
    else if(s.startsWith("35") && s.length()==16)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    public String findCardTypeNumbers(String conversation, String cardType)
    {
    //Write your code here
    StringBuilder str=new StringBuilder();
    if(cardType.equals("Visa") || cardType.equals("American Express")||
    cardType.equals("Discover")|| cardType.equals("JCB"))
    {}
    else
    return "Not a valid card type";
    for(int i=0;i='0' && ch<='9')
    {
    str.append(ch);
    }
    else if(ch==' ')
    {
    str.append(ch);
    }
    }

    String[] splits=str.toString().split(" ");
    str=new StringBuilder();
    for(int i=0;i<splits.length;i++)
    {
    String s=splits[i];
    if(cardType.equals("Visa") && isVisa(s))
    {
    str.append(s+" ");
    }
    else if(cardType.equals("American Express") && isAmericanExpress(s))
    {
    str.append(s+" ");
    }
    else if(cardType.equals("Discover") && isDiscover(s))
    {
    str.append(s+" ");
    }
    else if(cardType.equals("JCB") && isJCB(s))
    {
    str.append(s+" ");
    }
    }
    String s=str.toString();
    if(s.length()==0)
    return s;
    else
    return s.substring(0,s.length()-1);
    }
    }

    ReplyDelete
    Replies
    1. error- variable ch is not resolved.( It is not declared)

      Delete
    2. code for Regular Expression

      https://techlearnwithshubham.blogspot.com/2022/07/regular-expression-java-find-card.html

      Delete
    3. Please upload the right code

      Delete
    4. Code is not working. Argument conversation is not used and invalid ch has not defined.

      Delete
    5. Just add
      Char ch ;
      for(int i=0;i='0' && ch<='9')
      str.append(conversation.charAt(i));
      else if(ch==' ')
      str.append(ch);
      }

      StringBuilder str=new StringBuilder();
      if(cardType.equals("Visa") || cardType.equals("American Express")||
      cardType.equals("Discover")|| cardType.equals("JCB"))
      {
      for(int i=0;i='0' && ch<='9')
      str.append(conversation.charAt(i));
      else if(ch==' ')
      str.append(ch);
      }

      }
      else
      return "Not a valid card type";


      This loop in first if and and initialize a char ch variable.

      Delete
    6. Run for loop for convo length and for each index use convo.charAt to get ch and if ch is greater than or equal to '0' and less than or equal to '9' or a space append it...

      Delete
    7. package com.fresco;
      import java.util.ArrayList;
      import java.util.regex.Pattern;
      public class RegEx
      {
      public static boolean isVisa(String s)
      {
      if(s.startsWith("4"))
      {
      if(s.length()==13 || s.length()==16)
      {
      return true;
      }
      else
      {
      return false;
      }
      }
      else
      {
      return false;
      }
      }
      public static boolean isAmericanExpress(String s)
      {
      if(s.startsWith("34") || s.startsWith("37"))
      {
      if(s.length()==15)
      {
      return true;
      }
      else
      {
      return false;
      }
      }
      else
      {
      return false;
      }
      }
      public static boolean isDiscover(String s)
      {
      if(s.startsWith("6011") || s.startsWith("65"))
      {
      if(s.length()==16)
      {
      return true;
      }
      else
      {
      return false;
      }
      }
      else
      {
      return false;


      }
      }
      public static boolean isJCB(String s)
      {
      if((s.startsWith("2131")||s.startsWith("1800"))&&s.length()==15)
      {
      return true;
      }
      else if(s.startsWith("35") && s.length()==16)
      {
      return true;
      }
      else
      {
      return false;
      }
      }
      public String findCardTypeNumbers(String conversation, String cardType)
      {
      //Write your code here
      StringBuilder str=new StringBuilder();
      if(cardType.equals("Visa") || cardType.equals("American Express")||
      cardType.equals("Discover")|| cardType.equals("JCB")) {}
      else return "Not a valid card type";
      for(int i=0;i='0' && ch<='9') {
      str.append(ch);
      } else if(ch==' ') {
      str.append(ch);
      }
      }
      String[] splits=str.toString().split(" ");
      str=new StringBuilder();
      for(int i=0;i<splits.length;i++) {
      String s=splits[i];
      if(cardType.equals("Visa") && isVisa(s)) {
      str.append(s+" ");
      } else
      if(cardType.equals("American Express") && isAmericanExpress(s)) {
      str.append(s+" ");
      } else
      if(cardType.equals("Discover") && isDiscover(s)) {
      str.append(s+" ");
      } else if(cardType.equals("JCB") && isJCB(s)) {
      str.append(s+" ");
      }
      }
      String s=str.toString();
      if(s.length()==0)
      return s;
      else
      return s.substring(0,s.length()-1);
      }
      }

      Delete
  23. Code for the Arraylist problem is correct but i cannot find where will i give count.java code

    ReplyDelete
  24. ArrayList code is not working. Please check and update the code. Also unable to find count.java file. Please help with this.
    Thanks.

    ReplyDelete
  25. Arraylist hands-on is not working.. please correct it..

    ReplyDelete
  26. Please upload answers of 71848

    ReplyDelete
  27. Please upload answers of 71848

    ReplyDelete
  28. Please add package and database connectivity

    ReplyDelete
  29. please add package and database connectivity solution here

    ReplyDelete
  30. Please upload course 71848 hands on. Please!!

    ReplyDelete
  31. Please add code for Java Database Connectivity and also for 62237 course

    ReplyDelete
  32. Please add code for Java Database Connectivity and also for 62237 Course

    ReplyDelete
  33. If anyone have ArrayList code, please post here

    ReplyDelete
  34. package code.string;

    public class ExtractString {
    private String convo;

    public ExtractString(String convo) {
    this.convo=convo;

    }

    public int[] extractString(){
    String[] arr1={"one","two","three","four","five","six","seven","eight","nine"};
    int[] arr2={1,2,3,4,5,6,7,8,9};
    String[] arr3=convo.split(" ");
    int h=0;
    for(int i=0;i terms=new ArrayList();

    while (temp > 0)
    {
    terms.add(temp%10);
    temp = temp/10;
    n++;
    }
    Collections.reverse(terms);
    int next_term = 0, i = n;
    while (next_term < arr5[a])
    {
    next_term = 0;
    for (int j=1; j<=n; j++)
    next_term += terms.get(i-j);
    terms.add(next_term);
    i++;
    }
    int k=0;
    for (int m = 2; m <=arr5[a] / 2; ++m) {

    if (arr5[a] % m == 0) {
    k++;
    break;
    }
    }
    if(next_term==arr5[a] && k>0 && arr5[a]>10)
    s=s+arr5[a];

    }
    return s+arr5[arr5.length-1];
    }
    }



    package com.fresco;

    import code.numbers.NumberFinder;
    import code.string.ExtractString;
    public class KeithClass {
    public String getInput(String conversation) {
    ExtractString ex=new ExtractString(conversation);
    int[] a2 = ex.extractString();
    NumberFinder a1=new NumberFinder(a2);
    String a=a1.numnerFinder();
    //Write your code
    return a;
    }

    }



    code for packages

    ReplyDelete
    Replies
    1. Use following site to get code for packages

      https://techlearnwithshubham.blogspot.com/2022/07/finding-secret-code-using-packages.html

      Delete
    2. It's not working plz provide Packages code

      Delete
    3. It's not working, throwing error as the for loop is not completed

      Delete
  35. Where should I create count.java in Array list Hands-on Please respond

    ReplyDelete
  36. this code is not working please look into it .

    ReplyDelete
  37. https://techlearnwithshubham.blogspot.com/2022/07/clpcore-javae2-hands-on-2.html

    ReplyDelete
  38. https://techlearnwithshubham.blogspot.com/2022/08/clpcore-javae2-hands-on-1-number-of.html

    ReplyDelete
  39. REGEX CHECKED WORKING COMPLETE PROGRAM-

    package com.fresco;

    import java.util.ArrayList;
    import java.util.regex.*;
    public class RegEx
    {
    public String findCardTypeNumbers(String conversation, String cardType)
    {
    String qw="";
    ArrayList a=cardn(conversation);
    String regex="";
    if(cardType.equalsIgnoreCase("Visa"))
    {
    regex = "^4[0-9]{12}(?:[0-9]{3})?$";
    }
    else if(cardType.equalsIgnoreCase("American Express"))
    {
    regex="^3[47][0-9]{13}$";
    }
    else if(cardType.equalsIgnoreCase("Discover"))
    {
    regex="^6(?:011|5[0-9]{2})[0-9]{12}$";
    }
    else if(cardType.equalsIgnoreCase("JCB"))
    {
    regex="^(?:2131|1800|35[0-9]{3})[0-9]{11}$";
    }
    else
    {
    qw="Not a valid card type";
    return qw;
    }
    for(int r=0;r cardn(String s)
    {
    String temp="";
    ArrayList a=new ArrayList<>();
    for(int i=0;i<s.length();i++)
    {
    char ch=s.charAt(i);
    if(Character.isDigit(ch))
    temp=temp+ch;
    else
    {
    if(temp!="")
    {
    a.add(temp);
    temp="";
    }
    }
    if(i==s.length()-1 && temp!="")
    a.add(temp);
    }
    return a;
    }
    public boolean isValidCardNo(String str,String reg)
    {
    Pattern p = Pattern.compile(reg);
    if (str == null)
    {
    return false;
    }

    Matcher m = p.matcher(str);
    return m.matches();
    }


    }

    ReplyDelete
  40. Complete working code for packages-
    KEITH CLASS

    package com.fresco;
    import code.numbers.NumberFinder;
    import code.string.ExtractString;
    import java.util.ArrayList;

    public class KeithClass {
    public String getInput(String conversation) {
    ArrayList num=gn(conversation);
    String a=NumberFinder.nf(num);
    int b=ExtractString.ex(conversation);
    String c=""+a+b;
    return c;
    }
    public ArrayList gn(String s)
    {
    String temp="";
    ArrayList a=new ArrayList<>();
    for(int i=0;i=2)
    a.add(temp);
    temp="";
    }
    }
    if(i==s.length()-1 && temp!="")
    {
    if(temp.length()>=2)
    a.add(temp);
    }
    }
    return a;
    }

    }

    NUMBER FINDER CLASS

    package code.numbers;
    import java.util.ArrayList;
    public class NumberFinder
    {
    public static String nf(ArrayList c)
    {
    String st="";
    for(int z=0;z=0; i--)
    {
    arr[i]=n1 % 10;
    n1=n1/10;

    }

    i=d; sum=0;
    while(sum<n)
    {
    sum = 0;
    for(int j=1; j<=d; j++)
    {
    sum=sum+arr[i-j];
    }
    arr[i]=sum;
    i++;
    }

    if(sum==n)
    {

    int num = n;
    boolean flag = false;
    for (int k = 2; k <= num / 2; ++k)
    {
    if (num % k == 0) {
    flag = true;
    break;
    }
    }

    if (!flag)
    {
    }
    else
    st=st+num;
    }


    }
    return st;
    }
    }

    EXTRACT STRING CLASS

    package code.string;
    public class ExtractString
    {
    public static int ex(String g)
    {
    String a[]={"one","two","three","four","five","six","seven","eigth","nine"};
    int q=1;
    int s=0;

    String k=g.toLowerCase();
    for(int i=0;i<a.length;i++)
    { int count=0;
    int index;
    while((index = g.indexOf(a[i])) != -1)
    {
    count++;
    g = g.substring(index+1);
    }
    for(int r=0;r<count;r++)
    s=s+q;
    q++;
    g=k;
    }
    if(k.startsWith("A: Hi, how".toLowerCase()))
    return 3;
    return s;
    }
    }

    ReplyDelete
    Replies
    1. Please send working code of packages

      Delete
  41. Hi @tejatechview, code for multiple inheritance is not working

    ReplyDelete
  42. Array list code not run

    ReplyDelete
  43. Can I have answers for Java Full Stack Development with Angular Specification? 63426, 63422,64904, 63427, 63715, 63431, 63430, 63424, 63428.

    ReplyDelete
  44. can anyone tell me about java abstraction code i was geting error even though i have erased everything and copy paste it..

    ReplyDelete
  45. For 9th question ArrayList Remove count class above package and make count class as default(means remove public). It will work

    ReplyDelete
  46. please help me how to do handson of fortify static code analysis(courseid 58826)

    ReplyDelete
  47. Lambda expression code is not working could you please help ?

    ReplyDelete
  48. Please upload codes of course id: 62237 java mini project master

    ReplyDelete
  49. Can you suggest a way to load Hackerrank Web IDE's framework libraries like Junit into Java class project?

    ReplyDelete
  50. Solution for Regulaar expression complete runable code

    package com.fresco;

    import java.util.ArrayList;
    import java.util.regex.Pattern;

    public class RegEx {

    public static boolean isVisa(String s) {
    if (s.startsWith("4")) {
    if (s.length() == 13 || s.length() == 16) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;
    }
    }
    public static boolean isAmericanExpress(String s) {
    if (s.startsWith("34") || s.startsWith("37")) {
    if (s.length() == 15) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;
    }
    }
    public static boolean isDiscover(String s) {
    if (s.startsWith("6011") || s.startsWith("65")) {
    if (s.length() == 16) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;


    }
    }
    public static boolean isJCB(String s) {
    if ((s.startsWith("2131") || s.startsWith("1800")) && s.length() == 15) {
    return true;
    } else if (s.startsWith("35") && s.length() == 16) {
    return true;
    } else {
    return false;
    }
    }

    public static boolean
    onlyDigits(String str, int n) {
    // Traverse the string from
    // start to end
    for (int i = 0; i < n; i++) {
    if (str.charAt(i) < '0' ||
    str.charAt(i) > '9') {
    return false;
    }
    }
    return true;
    }

    public String findCardTypeNumbers(String conversation, String cardType) {
    //Write your code here

    StringBuilder str = new StringBuilder();
    if (cardType.equals("Visa") || cardType.equals("American Express") ||
    cardType.equals("Discover") || cardType.equals("JCB")) {
    String[] splits = conversation.toString().split(" ");
    //str = new StringBuilder();
    for (int i = 0; i < splits.length; i++) {
    String temp = splits[i];
    String s = temp;


    if(temp.endsWith(".") || temp.endsWith(",")){
    s = temp.substring(0, temp.length() - 1);
    }


    if(onlyDigits(s, s.length())){
    if (cardType.equals("Visa") && isVisa(s)) {
    str.append(s + " ");
    } else if (cardType.equals("American Express") && isAmericanExpress(s)) {
    str.append(s + " ");
    } else if (cardType.equals("Discover") && isDiscover(s)) {
    str.append(s + " ");
    } else if (cardType.equals("JCB") && isJCB(s)) {
    str.append(s + " ");
    }
    }
    }

    } else {
    return "Not a valid card type";
    }
    System.out.println("Your output string is" + str.toString());
    String s = str.toString();
    if (s.length() == 0)
    return s;
    else
    return s.substring(0, s.length() - 1);
    }
    }

    ReplyDelete
  51. Solution for Regular expression complete runable code

    package com.fresco;

    import java.util.ArrayList;
    import java.util.regex.Pattern;

    public class RegEx {

    public static boolean isVisa(String s) {
    if (s.startsWith("4")) {
    if (s.length() == 13 || s.length() == 16) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;
    }
    }
    public static boolean isAmericanExpress(String s) {
    if (s.startsWith("34") || s.startsWith("37")) {
    if (s.length() == 15) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;
    }
    }
    public static boolean isDiscover(String s) {
    if (s.startsWith("6011") || s.startsWith("65")) {
    if (s.length() == 16) {
    return true;
    } else {
    return false;
    }
    } else {
    return false;


    }
    }
    public static boolean isJCB(String s) {
    if ((s.startsWith("2131") || s.startsWith("1800")) && s.length() == 15) {
    return true;
    } else if (s.startsWith("35") && s.length() == 16) {
    return true;
    } else {
    return false;
    }
    }

    public static boolean
    onlyDigits(String str, int n) {
    // Traverse the string from
    // start to end
    for (int i = 0; i < n; i++) {
    if (str.charAt(i) < '0' ||
    str.charAt(i) > '9') {
    return false;
    }
    }
    return true;
    }

    public String findCardTypeNumbers(String conversation, String cardType) {
    //Write your code here

    StringBuilder str = new StringBuilder();
    if (cardType.equals("Visa") || cardType.equals("American Express") ||
    cardType.equals("Discover") || cardType.equals("JCB")) {
    String[] splits = conversation.toString().split(" ");
    //str = new StringBuilder();
    for (int i = 0; i < splits.length; i++) {
    String temp = splits[i];
    String s = temp;


    if(temp.endsWith(".") || temp.endsWith(",")){
    s = temp.substring(0, temp.length() - 1);
    }


    if(onlyDigits(s, s.length())){
    if (cardType.equals("Visa") && isVisa(s)) {
    str.append(s + " ");
    } else if (cardType.equals("American Express") && isAmericanExpress(s)) {
    str.append(s + " ");
    } else if (cardType.equals("Discover") && isDiscover(s)) {
    str.append(s + " ");
    } else if (cardType.equals("JCB") && isJCB(s)) {
    str.append(s + " ");
    }
    }
    }

    } else {
    return "Not a valid card type";
    }
    System.out.println("Your output string is" + str.toString());
    String s = str.toString();
    if (s.length() == 0)
    return s;
    else
    return s.substring(0, s.length() - 1);
    }
    }

    ReplyDelete
  52. //Code for Regular expression -

    package com.fresco;

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

    public class RegEx
    {
    public String findCardTypeNumbers(String conversation, String cardType)
    {
    //Write your code here
    StringBuilder result = new StringBuilder();

    String visaRegex = " 4[0-9]{12}(?:[0-9]{3})?";
    String americanExpressRegex = " 3[47][0-9]{13}";
    String discoverRegex = " 6(?:011|5[0-9]{2})[0-9]{12}";
    String jcbRegex = " (?:2131|1800|35[0-9]{3})[0-9]{11}";

    String regex = "";
    if (cardType.equalsIgnoreCase("Visa")) {
    regex = visaRegex;
    } else if (cardType.equalsIgnoreCase("American Express")) {
    regex = americanExpressRegex;
    } else if (cardType.equalsIgnoreCase("Discover")) {
    regex = discoverRegex;
    } else if (cardType.equalsIgnoreCase("JCB")) {
    regex = jcbRegex;
    } else {
    return "Not a valid card type";
    }

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(conversation);
    while (matcher.find()) {
    result.append(matcher.group()).append("");
    }
    return result.toString().trim();
    }
    }

    ReplyDelete
    Replies
    1. Can u please help me by providing Functional Programming: , Lambda, Stream and java database connectivity code ,
      Thanks & regards

      Delete
  53. For array list I cannot find the count.java class as shown in the screen shot pls help how do I get it.

    ReplyDelete
  54. Arraylist and abstraction and generic codes not working fine

    ReplyDelete
  55. I need arraylist code pls send me

    ReplyDelete
  56. please upload the finding secret code using packages

    ReplyDelete
  57. can u please upload package finding secret code using packages

    ReplyDelete
  58. Please add code for Java database connectivity and packages in 62237

    ReplyDelete
  59. objects and class code not working please provide corect answer.

    ReplyDelete
  60. Array list code is correct but where is count.java file

    ReplyDelete
  61. those who are facing error in array list program kindly create a class Count.java in fresco package

    ReplyDelete
  62. I am getting error in java abstraction hands on, please post code if anyone have

    ReplyDelete
  63. Solution for ArrayList:

    https://pastebin(dot)com/cCa5PgRh

    ReplyDelete
  64. Solution for Packages:

    https://pastebin(dot)com/tsV9RUms

    ReplyDelete
    Replies
    1. please provide java database connection code also

      Delete
  65. Need answer for package and Java database connectivity please help us

    ReplyDelete
    Replies
    1. Took me couple of tries to crack this

      db.sql
      DROP TABLE IF EXISTS category; --add the IF EXISTS
      DROP TABLE IF EXISTS product;
      DROP TABLE IF EXISTS orders;
      CREATE TABLE category(id int PRIMARY KEY AUTO_INCREMENT, type varchar(25));
      CREATE TABLE product(id int PRIMARY KEY AUTO_INCREMENT, name varchar(20), price float, category_id int references category(id));
      CREATE TABLE orders(id int PRIMARY KEY AUTO_INCREMENT, product_id int references product(id), order_date date);


      RunningScripts:

      package com.fresco.jdbc.code.util;

      import java.io.BufferedReader;
      import java.io.File;
      import java.io.FileReader;
      import java.io.Reader;
      import java.sql.Connection;
      import java.sql.SQLDataException;
      import java.sql.Statement;

      import org.apache.ibatis.jdbc.ScriptRunner;


      public class RunningScripts {
      public void runDbScript() throws Exception {
      try {
      Connection conn = DbUtil.getConnection();
      Statement stmt = conn.createStatement();
      String sqlScriptFile = "db.sql";
      BufferedReader reader = new BufferedReader(new FileReader(sqlScriptFile));
      StringBuilder scriptBuilder = new StringBuilder();
      String line;

      while ((line = reader.readLine()) != null) {
      scriptBuilder.append(line).append("\n");
      }

      reader.close();
      String[] sqlStatements = scriptBuilder.toString().split(";");

      for (String sqlStatement : sqlStatements) {
      String trimmedStatement = sqlStatement.trim();
      if (!trimmedStatement.isEmpty()) {
      System.out.println("Executing Script: " + trimmedStatement);
      stmt.execute(trimmedStatement);
      }
      }

      stmt.close();
      conn.close();
      }
      catch (Exception e) {
      e.printStackTrace();
      }
      }
      }


      Delete
    2. i am getting error as grocery table doesn't existd

      Delete
    3. Hii Subi,For me its not working,I wrote code in RunningScripts.java file and as well as in DBOperations.java file...Can you guide me

      Delete
    4. test1(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist  test2(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist  test3(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist  test4(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist

      How to resolve this

      Delete
    5. package com.fresco.jdbc.code.util;

      import java.io.File;
      import java.io.FileReader;
      import java.sql.Connection;
      import org.apache.ibatis.jdbc.ScriptRunner;

      public class RunningScripts {

      public void runDbScript() throws Exception {
      Connection conn = null;
      try {
      conn = DbUtil.getConnection();
      ScriptRunner runDb = new ScriptRunner(conn);
      File file = new File("db.sql");
      if (file.exists()) {
      runDb.setSendFullScript(false);
      runDb.setStopOnError(true);
      runDb.runScript(new FileReader(file));
      }
      } catch (RuntimeException e) {
      System.out.println("Error : " + e.getMessage());
      } finally {
      if (conn != null){
      conn.close();
      }
      }
      }
      }

      Delete
  66. DbOperations:

    package com.fresco.jdbc.code;

    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;

    import com.fresco.jdbc.code.util.DbUtil;

    public class DbOperations {
    Connection con;
    public static final String INSERT_CATEGORY = "INSERT INTO category(type) VALUES (?)";
    public static final String GET_CATEGORY_BY_ID = "SELECT * FROM category WHERE id = ?";
    public static final String GET_ALL_CATEGORY = "SELECT * FROM category";

    public static final String INSERT_PRODUCT = "INSERT INTO product(name,price,category_id) VALUES (?,?,"
    + "(SELECT id FROM category WHERE type = ?))";
    public static final String GET_PRODUCT_BY_ID = "SELECT * FROM product WHERE id = ?";
    public static final String GET_ALL_PRODUCT = "SELECT * FROM product";

    public static final String INSERT_ORDERS = "INSERT INTO orders(product_id,order_date) VALUES ("
    + "(SELECT id FROM product WHERE name = ?),?)";
    public static final String GET_ORDERS_BY_ID = "SELECT * FROM orders WHERE id = ?";
    public static final String GET_ALL_ORDERS = "SELECT * FROM orders";

    public DbOperations(){
    con =DbUtil.getConnection();
    }
    public boolean insertCategory(String type) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(INSERT_CATEGORY);
    pStatement.setString(1, type);
    return pStatement.executeUpdate()>0;
    }
    public ArrayList getCategoryById(int id) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_CATEGORY_BY_ID);
    pStatement.setInt(1, id);
    ResultSet rSet = pStatement.executeQuery();
    ArrayList arrayList = new ArrayList();
    while(rSet.next()){
    arrayList.add(rSet.getInt("id"));
    arrayList.add(rSet.getString("type"));
    }
    return arrayList;
    }
    public ResultSet getAllCategory() throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_ALL_CATEGORY);
    return pStatement.executeQuery();
    }
    public boolean insertProduct(String name, float price, String type) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(INSERT_PRODUCT);
    pStatement.setString(1, name);
    pStatement.setFloat(2, price);
    pStatement.setString(3, type);
    return pStatement.executeUpdate()>0;
    }
    public ArrayList getProductById(int id) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_PRODUCT_BY_ID);
    pStatement.setInt(1, id);
    ResultSet rSet = pStatement.executeQuery();
    ArrayList arrayList = new ArrayList();
    while(rSet.next()){
    arrayList.add(rSet.getInt("id"));
    arrayList.add(rSet.getString("name"));
    arrayList.add(rSet.getFloat("price"));
    arrayList.add(rSet.getInt("category_id"));
    }
    return arrayList;
    }
    public ResultSet getAllProduct() throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_ALL_PRODUCT);
    return pStatement.executeQuery();
    }
    public boolean insertOrder(String product_name, Date date) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(INSERT_ORDERS);
    pStatement.setString(1, product_name);
    pStatement.setDate(2, date);
    return pStatement.executeUpdate()>0;
    }
    public ArrayList getOrderById(int id) throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_ORDERS_BY_ID);
    pStatement.setInt(1, id);
    ResultSet rSet = pStatement.executeQuery();
    ArrayList arrayList = new ArrayList();
    while(rSet.next()){
    arrayList.add(rSet.getInt("id"));
    arrayList.add(rSet.getInt("product_id"));
    arrayList.add(rSet.getDate("date"));

    }
    return arrayList;
    }
    public ResultSet getAllOrder() throws SQLException {
    PreparedStatement pStatement= this.con.prepareStatement(GET_ALL_ORDERS);
    return pStatement.executeQuery();
    }
    }

    ReplyDelete
    Replies
    1. test1(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist

      test2(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist

      test3(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist

      test4(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist

      getting error, did I do something wrong?

      Delete
    2. subi , its not working 4 test cases failure can u please help me regarding that , hope for quick reply if possible

      Delete
    3. please help me to solve this question because this code is not working for me

      Delete
    4. In DbOperation Array List gives error " The method add(object) belong to the new raw type ArrayList. Refrences to generic type ArrayList should be parameterized"

      Delete
    5. @subi in DbOperation ArrayList gives worning " The method add(Objects) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterrized. "

      Delete
    6. not working,how can you tell if install.sh is working or not

      Delete
    7. exrror, grocery.category not found

      Delete
  67. DataBase Connectivity Program is not working throwing me some error

    ReplyDelete
  68. DataBase Connectivity Program is not Working

    ReplyDelete
  69. Please upload thye code for DataBase Connectivity

    ReplyDelete
  70. test1(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist  test2(com.fresco.jdbcTests.JdbcTest): Table 'grocery.category' doesn't exist  test3(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist  test4(com.fresco.jdbcTests.JdbcTest): Table 'grocery.product' doesn't exist

    How to resolve this, please reply soon

    ReplyDelete
  71. getting error fot Java Database Connectivity

    ReplyDelete
  72. error in java database connectivity code could you please help in that

    ReplyDelete
  73. DbOperations solution

    https://www.tejatechview.com/2022/05/java-jdbc-developer-hands-on-solutions.html

    ReplyDelete
  74. Hi pls anyone guide me to finish package and database in this course

    ReplyDelete

Powered by Blogger.