Вы находитесь на странице: 1из 17

CSE1007 – JAVA PROGRAMMING

Fall semester 2019~20


Slot: L5+L6
E-Record
Experiment No.:1-7
Submitted by
Name of the Student: KAUSTUBH SINGH
Reg. no.: 18BCE0722

DEPARTMENT OF COMPUTER SCIENCE


SCHOOL OF COMPUTER SCIENCE AND ENGINEERING
VELLORE INSTITUTE TECHNOLOGY
VELLORE-632014
TAMILNADU
INDIA

Date: 24/8/2019
1. Write a program to demonstrate the knowledge of students in basic Java concepts.
Eg., 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.parseFloa
t(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);

}
2. Write a program to demonstrate the knowledge of students in multidimensional arrays and
looping constructs.
Eg., 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);

3. Write a program to demonstrate the knowledge of students in String handling.


Eg., Write a program to read a chemical equation and find out the count of the reactants
and the products. Also display the count of the number of molecules of each reactant
and product.
Eg., For the equation, 2NaOH + H2SO4 -> Na2SO4+ 2H2O, the O/P should be as
follows.

Reactants are 2 moles of NaOH, 1 mole of H2SO4.

Products are 1 mole of Na2SO4 and 2 moles of H2O.

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");

4. Write a program to demonstrate the knowledge of students in advanced concepts of Java


string handling.
Eg., (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);

}
}
}

5. 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

a. The English film(s) that has Arnold as its lead actor and that runs for shortest
duration.
b. The Tamil film(s) with Rajini as lead actor.
c. 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();

6 Write a program to demonstrate the knowledge of students in creation of abstract classes and
working with abstract methods.
Eg., 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();

}
}

7 Write a program to demonstrate the knowledge of students in Java Exception handling.


Eg., Read the Register Number and Mobile Number of a student. If the Register Number
does not contain exactly 9 characters or if the Mobile Number does not contain exactly 10
characters, throw an IllegalArgumentException. If the Mobile Number contains any
character other than a digit, raise a NumberFormatException. If the Register Number
contains any character other than digits and alphabets, throw a NoSuchElementException. If
they are valid, print the message ‘valid’ else ‘invalid’

CODE:-

import
java.util.NoSuchElementException;
import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ExcepHandle{

static void validate(String r, String n){

if(r.length() != 9){

System.out.println("Invalid");

throw new
IllegalArgumentException("Register Number does not
contain exactly 9 characters");

if(n.length() != 10){

System.out.println("Invalid");

throw new IllegalArgumentException("Mobile


Number does not contain exactly 10 characters");

}
String pattern = "^[6|7|8|9]{1}\\d{9}";

Pattern a = Pattern.compile(pattern);

Matcher m1 = a.matcher(n);

if(!m1.find()){

throw new NumberFormatException("Mobile


Number cannot contain any character other than a
digit");

String pattern2 = "^[1-9]{2}[A-Z]{3}[0-9]{4}$";

Pattern b = Pattern.compile(pattern2);

Matcher m2 = b.matcher(r);

if(!m2.find()){

throw new
NoSuchElementException("Registration Number cannot
contain any character other than digits and
alphabets");

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

String reg = sc.nextLine();

String no = sc.nextLine();

sc.close();

validate(reg, no);

System.out.println("Valid");

}
}

Вам также может понравиться