11 Jan 2019

CSE1007: Java. Winter Semester 2018-19 lab problems.


-------------------------------------------
So, i used to run this blog back in 2nd semester, for skillrack problems for the OOPS with C++ course, now in the 6th semester i find that a lot of us have been coerced into taking the java course and the lab problems being given by professors are to a significant degree the same for all classes...
   ...So instead of sending my files to friends individually i've decided to dig up this forgotten grave of a blog and make one last post that i will keep updating over this semester as i do my lab tasks. 
    I will be following the cycle sheet that is being followed in my class and i'm told in some other classes too, and some professors that are not following it also happen to have coinciding questions so you will probably find some of your assignments here if not all. if however there is a popular question in other classes not being given in my class, DM me or drop in in the comments and i'll try to do that as well. 
Tl;dr = will post my java codes here; you may find most or some of what you need; dm/comment for requests; jet fuel can't melt steel beams; i used lower case i for the pronoun and this font which makes me artsy af (thats how it works just ask rupi kaur). 
-----------------------------------------

Nuff said..

 

----Question 1----

Write a program to read the First name and Last name of a person, his weight and height using command line arguments. Calculate the BMI Index which is defined as the individual's body mass divided by the square of their height.
Category
BMI Range-Kg/m2
Underweight
<18.5
Normal (healthy weight)
18.5 to 25
Overweight
25 to 30
Obese Class
Over 30
Display the name and display his category based on the BMI value thus calculated.

Code: 

import java.io.*;
import java.util.Scanner;
class ct0{
    public static void main(String[] args){
        float bmi=Float.parseFloat(args[1])/Float.parseFloat(args[2])/Float.parseFloat(args[2]);
         String c;
        if (bmi<18.5
            c="Underweight";
        else if (bmi<25)
            c="Normal";
        else if (bmi<30)
            c="overweight";
        else
            c="obese";
        System.out.println(args[0]+" "+c);
    }
}

Output:


 

----Question 2----

If there are 4 batches in BTech(IT) learning ‘ITE2005’ 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.

Code:

import java.io.*;
import java.util.Scanner;
class ct1{
    public static void main(String[] args){
        System.out.println(Integer.parseInt("10")+Integer.valueOf("10a"));
        Scanner in=new Scanner(System.in);
        int i,n,x,j;
        int[][] ja=new int[4][];
         for( i=0;i<4; i++){
            System.out.println("input number of students in batch"+(i+1));
            x=in.nextInt();
            n=(x/4)+((x/4)*4==x?0:1);
            ja[i]=new int[n];
            for(j=0;j<n;j++,x-=4) ja[i][j]=x>4?4:x;
        }
        System.out.println("array made, now we parse:");
        int tot=0;
        for( i=0;i<4; i++){
            System.out.println("");
            System.out.println("batch "+(i+1));
            for(j=0;j<ja[i].length;j++){
                System.out.print(ja[i][j]+", ");
                if(ja[i][j]==4) tot++;
            }
        }
        System.out.println("total number of full groups is:"+tot);
    }
}

Output:

----Question 3----

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.

Code:

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


class ct2{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        String e=in.nextLine();
        int i;
        System.out.print("Reactants are:");
        for(String p : e.split("-")[0].split(" ")){
            if(p.charAt(0)>='A' && p.charAt(0)<='Z') System.out.print("1 mole of "+p);
            else if(p.charAt(0)>='0' && p.charAt(0)<='9'){
                for(i=0;i<p.length() && p.charAt(i)>='0' && p.charAt(i)<='9';i++);
                System.out.print(p.substring(0,i));
                System.out.print(" mole of "+p.substring(i)+", ");
            }
        }
        System.out.print("\n Products are:");
        for(String p : e.split("-")[1].split(" ")){
            if(p.charAt(0)>='A' && p.charAt(0)<='Z') System.out.print("1 mole of "+p);
            else if(p.charAt(0)>='0' && p.charAt(0)<='9'){
                for(i=0;i<p.length() && p.charAt(i)>='0' && p.charAt(i)<='9';i++);
                System.out.print(p.substring(0,i));
                System.out.print(" mole of "+p.substring(i)+", ");
            }
        }
        System.out.print("\n");
    }
}

Output:



----Question 4----

(Bioinformatics: finding genes) Biologists use a sequence of letters A, C, T, and G to model a genome. A gene is a substring of a genome that starts after a triplet ATG and ends before a triplet TAG, TAA, or TGA. Furthermore, the length of a gene string is a multiple of 3 and the gene does not contain any of the triplets ATG, TAG, TAA, and TGA. Write a program that prompts the user to enter a genome and displays all genes in the genome. If no gene is found in the input sequence, displays no gene. Here are the sample runs:
Enter a genome string: TTATGTTTTAAGGATGGGGCGTTAGTT
O/P: TTT
GGGCGT

Code:

import java.io.*;
import java.util.Scanner;
class ct3{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        String e=in.nextLine(), g="",a="",b="",c="";
        int i;
        boolean x = false;
        for(String p : e.split("ATG")){
            i=p.length();
            a=p.split("TAG")[0];
            b=p.split("TAA")[0];
            c=p.split("TGA")[0];
            if(a.length()!=p.length() && a.length()%3==0) {i=a.length(); g=a;}
            if(b.length()!=p.length() && b.length()%3==0 && b.length()<i) {i=b.length(); g=b;}
            if(c.length()!=p.length() && c.length()%3==0 && c.length()<i) {i=c.length(); g=c;}
            if (i<p.length()) System.out.println(g);    
        }
    }
}

Output:





----Question 5----

  1. Write a program to demonstrate the knowledge of students in working with classes and objects.
Eg.,Create a class Film with string objects which stores name, language and lead_actor and category (action/drama/fiction/comedy). Also include an integer data member that stores the duration of the film. Include parameterized constructor, default constructor and accessory functions to film class. Flim objects can be initialized either using a constructor or accessor functions. Create a class FilmMain that includes a main function. In the main function create a vector object that stores the information about the film as objects. Use the suitable methods of vector class to iterate the vector object to display the following
  1. The English film(s) that has Arnold as its lead actor and that runs for shortest duration.
  2. The Tamil film(s) with Rajini as lead actor.
  3. All the comedy movies.

    Code: 

    import java.io.*;
    import java.util.Scanner;
    import java.util.Vector;
    import java.util.Iterator;
    class Film{
        public String name, lang, lead_actor, category;
        public int dur;
        public Film(){
            name="";
            lang="";
            lead_actor="";
            category="";
            dur=0;
        }
        public Film(String a,String b,String c,String d, int e){
            this.set(a,b,c,d,e);
        }
        public void set(String a,String b,String c,String d, int e){
            name=a;
            lang=b;
            lead_actor=c;
            category=d;
            dur=e;
        }
        public void prnt(){
            System.out.println(name+", "+lang+", "+lead_actor+", "+category+", "+dur);
        }
    }
    public class FilmMain{
        public static void main(String[] args){
            Scanner in=new Scanner(System.in);
            Vector<Film> v = new Vector<Film>();
            v.add(new Film("Terminator","English","Arnold","action",123));
            v.add(new Film("Apdi123","Tamil","Rajini","comedy",123));
            v.add(new Film("Terminator:outtakes","English","Arnold","comedy",11));
            Iterator<Film> it1=v.iterator();
            Iterator<Film> it2=v.iterator();
            Iterator<Film> it3=v.iterator();
            System.out.println("\n\na. The English film(s) that has Arnold as its lead actor and that runs for shortest duration.=");
            int s=999;
            Film y=new Film();
            while(it1.hasNext()){
                Film x=it1.next();
                if (x.lead_actor.equalsIgnoreCase("arnold") && x.dur<s){
                    s=x.dur;
                    y=x;
                }
            }
            y.prnt();
            System.out.println("\n\nb. The Tamil film(s) with Rajini as lead actor.=");
            while(it2.hasNext()){
                Film x=it2.next();
                if (x.lead_actor.equalsIgnoreCase("rajini")) x.prnt();
            }

            System.out.println("\n\nc. All the comedy movies.=");
            while(it3.hasNext()){
                Film x=it3.next();
                if (x.category.equalsIgnoreCase("comedy")) x.prnt();
            }
        }
    }

     


    Output:

     

     

    ----Question 6----

     

    Define an abstract class ‘Themepark’ and inherit 2 classes ‘Queensland’ and ‘Wonderla’ from the abstract class. In both the theme parks, the entrance fee for adults is Rs. 500 and for children it is Rs. 300. If a family buys ‘n’ adult tickets and ‘m’ children tickets, define a method in the abstract class to calculate the total cost. Also, declare an abstract method playGame() which must be redefined in the subclasses.
    In Queensland, there are a total of 30 games. Hence create a Boolean array named ‘Games’ of size 30 which initially stores false values for all the elements. If the player enters any game code that has already been played, a warning message should be displayed and the user should be asked for another choice. In Wonderla, there are a total of 40 different games. Thus create an integer array with 40 elements. Here, the games can be replayed, until the user wants to quit. Finally display the total count of games that were repeated and count of the games which were not played at all.

    Code:

    import java.io.*;
    import java.util.Scanner;
    import java.util.Vector;
    import java.util.Arrays;
    import java.util.Iterator;
    abstract class themepark{
        public int total_cost(int m,int n){
            return 500*n+300*m;
        }
        abstract void playGame();
    }
    class Queensland extends themepark{
        public void playGame(){
            Scanner in=new Scanner(System.in);
            boolean[] Games=new boolean[30];
            Arrays.fill(Games, false);
            boolean wtp=true;
            while(wtp){
                System.out.println("which game do you want to play? (1-30). 0 to quit");
                int x=in.nextInt();
                if(x==0) wtp=false;
                else if(x>30 || x<1) System.out.println("please input valid number");
                else if(Games[x]==true) System.out.println("Warning! play each game atmost once.");
                else{
                    System.out.println("Sucessfully played game "+x);
                    Games[x]=true;
                }
            }
        }
    }
    class Wonderla extends themepark{
        public void playGame(){
            Scanner in=new Scanner(System.in);
            int[] Games=new int[40];
            Arrays.fill(Games, 0);
            boolean wtp=true;
            while(wtp){
                System.out.println("which game do you want to play? (1-40). 0 to quit");
                int x=in.nextInt();
                if(x==0) wtp=false;
                else if(x>40 || x<1) System.out.println("please input valid number");
                else{
                    System.out.println("Sucessfully played game "+x);
                    Games[x]++;
                }
            }
            System.out.println("Games repeated=");
            for(int i=0;i<40;i++) if(Games[i]>1) System.out.print(i+", ");
            System.out.println("\nGames not played=");
            for(int i=0;i<40;i++) if(Games[i]==0) System.out.print(i+", ");
            System.out.println("\nGames played once=");
            for(int i=0;i<40;i++) if(Games[i]==1) System.out.print(i+", ");
        }
    }
    public class thmprk{

        public static void main(String[] args) {
            System.out.println("\n\nQueensland:");
            new Queensland().playGame();
            System.out.println("\n\nWonderla:");
            new Wonderla().playGame();
        }
    }

     

    Output:

     

     

     

    ----Question 8----

     

    1. Write a program to demonstrate the knowledge of students in working with user-defined packages and sub-packages.
    Eg., Within the package named ‘primespackage’, define a class Primes which includes a method checkForPrime() for checking if the given number is prime or not. Define another class named TwinPrimes outside of this package which will display all the pairs of prime numbers whose difference is 2. (Eg, within the range 1 to 10, all possible twin prime numbers are (3,5), (5,7)). The TwinPrimes class should make use of the checkForPrime() method in the Primes class.

     

    Code: 

     

     File= Primes.java


    package primespackage;
    public class Primes{
        public static boolean checkForPrime(int a){
            if(a<4) return a>1;
            for(int i=2;i<a/2;i++) if (a%i==0) return false;
            return true;
            //not optimal algorithm for primality test, trivial;
            //you can improve complexity if you want,
            //your VIT professor won't care much for it though...
        }
    }

     File= TwinPrimes.java


    import java.util.*;
    import java.io.*;
    import primespackage.Primes;
    class TwinPrimes{
            public static void main(String[] args){
            Scanner in=new Scanner(System.in);
            System.out.println("input limit to check for twin primes till:");
            int n=in.nextInt();
            if (n<5) return;
            for(int i=3;i+1<n;i+=4){
                if(Primes.checkForPrime(i)&&Primes.checkForPrime(i+2)) System.out.println(i+", "+(i+2));
                if(i+2<n&&Primes.checkForPrime(i+1)&&Primes.checkForPrime(i+3)) System.out.println((i+1)+", "+(i+3));
            }
        }
    }

    Terminal Output: 

    Do exactly this when you've 'cd'd into in the directory you saved these two files in.

    rohan@AE86:~/src/java$ javac -d . Primes.java
    rohan@AE86:~/src/java$ javac  TwinPrimes.java
    rohan@AE86:~/src/java$ java TwinPrimes
    input limit to check for twin primes till:
    500
    3, 5
    11, 13
    59, 61
    71, 73
    107, 109
    179, 181
    191, 193
    227, 229
    239, 241
    311, 313
    347, 349
    419, 421
    431, 433
    rohan@AE86:~/src/java$

     

     

5 comments:

  1. 1. Write a Java program to display all the prime numbers within a range.
    2. Write a Java program to convert a decimal number to its equivalent binary number.
    Eg: 25 base 10 = 11001 base 2
    3. Write a Java program to print the following patterns by reading the number of lines
    from the user.
    i)
    *
    **
    ***
    ****
    *****
    ii)
    *
    **
    ***
    ****
    *****
    iii)
    *
    **
    ***
    ****
    ***
    **
    *
    4. Write a Java program to sum up all the digits of an integer till the sum is a single digit. Eg: INPUT -> 9985
    9+9+8+5 = 31
    3+1 = 4
    OUTPUT -> 4
    5. Write a Java program to sort a numerical array using selection sort algorithm and remove all the duplicates from the same array. [Hint: Use single array]
    6. Write a Java program to read an integer ‘n’ from the user and display the multiplication table of ‘n’.
    7. Write a Java program to list out the elements in an array having mid property. An element in an array is said to have the mid property if its left element is lesser than it and also the right element is greater then it.
    Eg: ..... , 3, 5, 9, ....5 is having mid property.
    8. Print Hailstone sequence for a number.
    (Note: Take any positive integer n. If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.)Eg. Hailstone sequence of 15 is
    15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1
    9. Find whether an entered number is CIRCULAR PRIME or not. Display YES if it is a circular prime, otherwise display NO. A circular prime number is a number that remains prime on any cyclic rotation of its digits (in base 10).
    For example 1193 is circular prime because 1931, 9311, 3119 and 1193 are all prime numbers.
    10. Write a Java program to find out the greatest common divisor of two input values using a function.
    11. Write a Java program to reverse the contents of the array using different functions for different types of array (without using any secondary array for reversing).
    12. Write a Java program to check the given string is palindrome or not.
    13. Write a Java program to insert a string into another string and delete a substring from a
    string.
    14. Write a Java program to find out the number of occurrences of a pattern string in a given
    text.
    15. Write a Java program to swap two values in a SWAP( ) method using wrapper classes.
    16. Write a Java program to convert the decimal number to binary, octal, and hexadecimal
    numbers using wrapper class methods. [Hint: Integer and Long classes]
    17. Write a class definition for ‘stu’ with name, regno, and cgpa values and required methods as members of the class. Create an array of objects of ‘stu’ for ‘n’ number of students in G2 slot. Write a Java program to display the name and registration numbers
    of the students who have CGPA less than 4 in G2 slot.
    18. Write a Java program to implement complex number arithmetic using classes and use
    multiple constructors for initializing the complex numbers.
    19. Write a Java program to print a pattern using a method PRINT( ) as follows:
    *
    **
    ***
    ****
    *****
    The type of the character and/or the number of lines to be printed can be taken as input from the user. The default values are ‘*’ and 5. Using the concept of method overloading write different definitions for PRINT( ) with different argument list.

    ReplyDelete
  2. Bhai kardho na....Will be useful for students of our class

    ReplyDelete
  3. 11. Write a program to demonstrate the knowledge of students in creating and deploying applets.
    Eg., Draw a ball, filled with default color. Move the ball from top to bottom of the window continuously with its color changed for every one second. The new color of the ball for the next second should be obtained by adding 20 to the current value of Red component, for the second time by adding 20 to the blue component, and for the third time by adding 20 to the blue component, till all reach the final limit 225, after which the process should be repeated with the default color.

    ReplyDelete
  4. 1. Scenario: An advertising campaign consists of a set of advertisements. Adverts can be of several types, for example: a roadside Hoarding, a Newsapaper ad, TV commercial, or Poster. Each type of advert has a cost associated with it: a fixed fee to cover materials, production staff and media costs, and variable costs for buying advertising time and space. An advertising campaign consists of one or more advert-events:
    • A Hoarding for a poster is hired for a number of days. Assume a standard cost per hoarding. An additional surcharge of 50% can be charged for prime locations.
    • Newspaper: assume a cost/ per column
    • TV commercial: Air time is sold by the seconds. Assume a standard cost per second, which doubles at peak times.
    • Poster, which may have attributes such as dimensions, number of copies and cost per copy.
    Create a suite of classes Hoarding, poster, NewspaperAd, TVAd, with Advertcampaign as the base class. Include a dynamic method cost() in both base class and all subclasses to demonstrate the different ways of accessing the fee defined in the parent class, Advertcampaign. Create a JAVA application using polymorphism for displaying the cost details of the advertisement campaign that includes the variety of adverts.

    ReplyDelete
  5. Prepare two lists of CSE1007-Java Programming marks of A1+TA1 and
    A2+TA2 slot students and compute the following:
    a. All marks in both the slots without any duplicates
    b. Marks appear in both the slots
    c. Marks available only in A1+TA1, not in A2+TA2
    d. Marks available only in A2+TA2, not in A1+TA1

    ReplyDelete