· 6 years ago · Apr 01, 2019, 04:02 PM
1NAME: Aseem Sarvapriya
2REG. NO: 16BIT0303
3CSE1007 – JAVA PROGRAMMING
4LAB – 1 & 2
5Question 1: Find the largest number among three.
6CODE:
7import java.util.*;
8public class Largest
9{
10public static void main(String[] args)
11{
12Scanner sc =new Scanner(System.in);
13int n1= sc.nextInt();
14int n2= sc.nextInt();
15int n3= sc.nextInt();
16if( n1 >= n2 && n1 >= n3)
17 System.out.println(n1 + " is the largest number.");
18 else if (n2 >= n1 && n2 >= n3)
19 System.out.println(n2 + " is the largest number.");
20 else
21 System.out.println(n3 + " is the largest number.");
22}
23}
24Question 2: Generate Fibonacci series:
25CODE:
26import java.util.*;
27public class Fibonacci
28{
29public static void main(String[] args)
30{
31Scanner a=new Scanner(System.in);
32int n= a.nextInt();
33 int t1 = 0, t2 = 1;
34 System.out.print("First " + n + " terms: ");
35 for (int i = 1; i <= n; ++i)
36 {
37 System.out.print(t1 + " + ");
38 int sum = t1 + t2;
39 t1 = t2;
40 t2 = sum;
41 }
42}
43}
44Question 3: Check if number is Armstrong.
45CODE:
46import java.util.*;
47public class Armstrong
48{
49public static void main(String[] args)
50{
51int sum=0,n,a,temp;
52Scanner s=new Scanner(System.in);
53n=s.nextInt();
54temp=n;
55while(n>0)
56{
57a=n%10;
58n=n/10;
59sum=sum+(a*a*a);
60}
61 if(temp==sum)
62 System.out.println("armstrong number");
63 else
64 System.out.println("Not armstrong number");
65}
66}
67Question 4: Find first 50 prime numbers.
68CODE:
69public class Prime
70{
71 public static void main(String[] args)
72 {
73 int count = 0, max_count = 50, i;
74 System.out.println("First "+max_count+" Prime Numbers:");
75 for(int num=1; count<max_count; num++)
76 {
77 for(i=2; num%i != 0; i++);
78 if(i == num)
79 {
80 System.out.print(" "+num);
81 count++;
82 }
83 }
84 }
85}
86Question 5: Find the k smallest and k largest element in an array.
87CODE:
88import java.util.*;
89public class Knumber
90{
91public static void main(String[] args)
92{
93 Integer arr[] = new Integer[]{12, 3, 5, 7, 19};
94 Arrays.sort(arr);
95 int k1 = 2;
96 System.out.println( "K'th smallest element is "+ arr[k1]);
97 Arrays.sort(arr,Collections.reverseOrder());
98 int k2 = 2;
99 System.out.print( "K'th Largest element is "+ arr[k2]);
100
101}
102}
103Question 6: Sort the element in descending order.
104CODE:
105import java.util.*;
106public class DescendingOrder
107{
108 public static void main(String[] args)
109 {
110 int n, temp;
111 Integer arr[] = new Integer[]{12, 3, 5, 7, 19, 22, 40, 50};
112 n=arr.length;
113 for (int i = 0; i < n; i++)
114 {
115 for (int j = i + 1; j < n; j++)
116 {
117 if (arr[i] < arr[j])
118 {
119 temp = arr[i];
120 arr[i] = arr[j];
121 arr[j] = temp;
122 }
123 }
124 }
125 System.out.print("Descending Order:");
126 for (int i = 0; i < n - 1; i++)
127 {
128 System.out.print(arr[i] + ",");
129 }
130 System.out.print(arr[n - 1]);
131 }
132}
133Question 7: Write a program for matrix multiplication.
134CODE:
135class Matrixmultiplication
136{
137public static void main(String args[])
138int a[][]={{1,2,3},{4,5,6},{7,8,9}};
139int b[][]={{1,2,3},{4,5,6},{7,8,9}};
140 int c[][]=new int[3][3];
141 for(int i=0;i<3;i++)
142 {
143 for(int j=0;j<3;j++)
144 {
145 c[i][j]=0;
146 for(int k=0;k<3;k++)
147 {
148 c[i][j]+=a[i][k]*b[k][j];
149 }
150 System.out.print(c[i][j]+" ");
151 }
152 System.out.println();
153 }
154}
155}
156Question 8: Write a program to find transpose of a matrix.
157CODE:
158class Transposematrix
159{
160 public static void main(String args[])
161 {
162int i, j;
163int a[][]={{1,2,3},{4,5,6},{7,8,9}};
164System.out.println("The above matrix after Transpose is ");
165 for(i = 0; i < 3; i++)
166 {
167 for(j = 0; j < 3; j++)
168 {
169 System.out.print(a[j][i]+" ");
170 }
171 System.out.println(" ");
172 }
173 }
174}
175Question 9: Write a program to demonstrate the knowledge of students in multidimensional arrays and
176looping constructs. E.g., If there are 4 batches in BTech - “CSE1007†course, read the count of the
177slow learners (who have scored <25) in each batch. Tutors should be assigned in the ratio of 1:4 (For
178every 4 slow learners, there should be one tutor). Determine the number of tutors for each batch.
179Create a 2-D jagged array with 4 rows to store the count of slow learners in the 4 batches. The number
180of columns in each row should be equal to the number of groups formed for that particular batch ( Eg., If
181there are 23 slow learners in a batch, then there should be 6 tutors and in the jagged array, the
182corresponding row should store 4, 4, 4, 4, 4,3). Use for-each loop to traverse the array and print the
183details. Also print the number of batches in which all tutors have exactly 4 students.
184CODE:
185import java.util.*;
186class Slowlearners
187{
188public static void main(String args[])
189{
190Scanner s = new Scanner(System.in);
191int sl[] = new int[4];
192int no_batch[] = new int[4];
193System.out.println("Enter count of slow learners in first batch");
194sl[0] = s.nextInt();
195System.out.println("Enter count of slow learners in second batch");
196sl[1] = s.nextInt();
197System.out.println("Enter count of slow learners in third batch");
198sl[2] = s.nextInt();
199System.out.println("Enter count of slow learners in fourth batch");
200sl[3] = s.nextInt();
201for(int i=0;i<4;i++)
202{
203no_batch[i] = sl[i]/4;
204if(((sl[i]%4)!=0))
205{
206no_batch[i]++;
207}
208}
209int jarr[][] = new int[4][];
210for(int i=0;i<4;i++)
211{
212jarr[i] = new int[no_batch[i]];
213}
214for(int i=0;i<4;i++)
215{
216for(int j=0;j<no_batch[i];j++)
217{
218if(j!=(no_batch[i]-1))
219{
220jarr[i][j]=4;
221}
222if(j==(no_batch[i]-1))
223{
224if((sl[i]%4)==0)
225{
226jarr[i][j]=4;
227}
228else if((sl[i]%4)!=0)
229{
230jarr[i][j]=(sl[i]%4);
231}
232}
233}
234}
235for(int i=0;i<4;i++)
236{
237for(int j=0;j<no_batch[i];j++)
238{
239System.out.print(jarr[i][j] + " ");
240}
241System.out.println("");
242}
243}
244}
245Question 10: Design a class named Rectangle to represent a rectangle. The class contains: Two double
246data fields named width and height that specify the width and height of the rectangle. The default values
247are 1 for both width and height. A default constructor that creates a default rectangle. A constructor that
248creates a rectangle with the specified width and height. A method named getArea() that returns the area
249of this rectangle. A method named getPerimeter() that returns the perimeter. Implement the class. Write
250a test program that creates two Rectangle objects— one with width 5 and height 50 and the other with
251width 2.5 and height 45.7. Display the width, height, area, and perimeter of each rectangle in this order.
252CODE:
253class Rectangle
254{
255double width;
256double height;
257Rectangle()
258{
259width = 1; height = 1;
260}
261Rectangle(double w, double h)
262{
263width = w; height = h;
264}
265double getArea()
266{
267double area;
268area = width*height;
269return area;
270}
271double getPerimeter()
272{
273double perimeter;
274perimeter = 2*(width + height);
275return perimeter;
276}
277void display()
278{
279System.out.println("Width: "+width+"\n Height: "+height+"\n Area:
280"+this.getArea()+"\n Perimeter: "+this.getPerimeter());
281}
282public static void main(String args[])
283{
284Rectangle r1 = new Rectangle(5,50);
285Rectangle r2 = new Rectangle(2.5,45.7);
286System.out.println("First Rectangle");
287r1.display();
288System.out.println("Second Rectangle");
289r2.display();
290}
291}
292Question 11. Write a Java program to create a class called Student having data members Regno, Name,
293Course being studied and current CGPA. Include constructor to initialize objects. Create array of objects
294with at least 10 students and find 9- pointers.
295CODE:
296class Student
297{
298int registerno;
299String Name;
300String Course;
301double CGPA;
302Student(int r, String n, String c, double cg)
303{
304registerno = r; Name = n; Course = c; CGPA = cg;
305}
306public static void main(String args[])
307{
308Student s[] = new Student[10];
309String names[] =
310{"Aseem","Shivam","Chetan","Piyush","Sourav","Abhinav","Yash","Akash","Tanmay","Haris
311h"};
312double CGPAS[] = {9.3,7.5,7.7,9.9,8.5,6.7,7.9,9.3,6.7,9.6};
313for(int i=0;i<10;i++)
314{
315s[i] = new Student(i+1,names[i],"Java",CGPAS[i]);
316}
317System.out.println("9 Pointers list: \n");
318for(Student st:s)
319{
320if(st.CGPA>=9.0)
321{
322System.out.println("Reg. No: "+st.registerno+"Name:
323"+st.Name+"\n");
324}
325}
326}
327}
328Question 12. Write a Java program that displays area of different Figures (Rectangle, Square, Triangle)
329using the method overloading.
330CODE:
331class Figures
332{
333void getArea(double width,double height)
334{
335double area = (width*height);
336System.out.println("Area of rectangle is: "+area+"\n");
337}
338void getArea(double sq)
339{
340double area = (Math.pow(sq,2));
341System.out.println("Area of square is: "+area+"\n");
342}
343void getArea(double tri_b,double tri_h,double triangle)
344{
345double area = (0.5*tri_b*tri_h);
346System.out.println("Area of triangle is: "+area+"\n");
347}
348public static void main(String args[])
349{
350Figures fig_rec = new Figures();
351Figures fig_sq = new Figures();
352Figures fig_tr = new Figures();
353fig_rec.getArea(8,20);
354fig_sq.getArea(5);
355fig_tr.getArea(5,7,2);
356}
357}
358Question 13. Write a Java program that displays that displays the time in different formats in the form of
359HH, MM, SS using constructor Overloading.
360CODE:
361import java.util.*;
362class Time
363{
364int hrs; int min; int sec;
365Time(int h, int m, int s)
366{
367System.out.println("Current Time in HH:MM:SS format is:
368"+h+":"+m+":"+s);
369}
370Time(int h, int m, int s,int format)
371{
372String am_pm = "am";
373if(h>12)
374{
375h=h-12; am_pm = "pm";
376}
377System.out.println("Current Time in HH:MM:SS - 12hr format is:
378"+h+":"+m+":"+s+" "+am_pm);
379}
380public static void main(String args[])
381{
382int hours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
383int minutes = Calendar.getInstance().get(Calendar.MINUTE);
384int seconds = Calendar.getInstance().get(Calendar.SECOND);
385Time t = new Time(hours,minutes,seconds);
386Time t1 = new Time(hours,minutes,seconds,12);
387}
388}
389Question 14. In a school, students of all classes from std I to X appear for the MathPremierLeague
390examination. Define a class MPL which stores the details of the marks scored by each class. It should
391contain the following 4 data members: Standard, number of students, marks[] array to store the scores of
392all the students of the class in MPL exam and first mark. Define a parameterized constructor which
393receives the values for the first two data members from the main() method. Create a From within the
394constructor, read the marks of all students and hence find the first mark. Define a method findBestClass()
395to display the standard which has secured the highest first mark. Overload this method to display the
396standard with the highest-class average. The marks array should be declared dynamically based on the
397strength of the class.
398CODE:
399import java.util.*;
400class MPL
401{
402int standard;
403int nos;
404int[] marks;
405int firstMark;
406MPL(int s,int no)
407{
408standard = s;
409nos = no;
410Scanner sc = new Scanner(System.in);
411marks = new int[no];
412System.out.println("Enter Marks for the class "+s);
413for(int i=0;i<no;i++)
414{
415marks[i] = sc.nextInt();
416}
417int highest = -99;
418for(int i:marks)
419{
420if(i>highest)
421{
422highest = i;
423}
424firstMark=highest;
425}
426}
427int findBestClass()
428{
429 return firstMark;
430}
431double findBestClass(double avg)
432{
433double sum = 0;
434for(int i=0;i<marks.length;i++)
435{
436sum+=marks[i];
437}
438avg = (sum/marks.length);
439return avg;
440}
441public static void main(String args[])
442{
443MPL m[] = new MPL[2];
444m[0] = new MPL(8,5);
445m[1] = new MPL(10,7);
446int highest = -99;
447int standardh = 0;
448for(int i=0;i<m.length;i++)
449{
450int res = m[i].findBestClass();
451if(res>highest)
452{
453highest = res;
454standardh = m[i].standard;
455}
456}
457System.out.println("Standard with highest first Mark: "+ standardh);
458double highestavg = -99;
459int standardavg = 0;
460for(int i=0;i<m.length;i++)
461{
462double res = m[i].findBestClass(0);
463if(res>highestavg)
464{
465highestavg = res;
466standardavg = m[i].standard;
467}
468}
469System.out.println("Standard with highest class average: "+
470standardavg);
471}
472}
473NAME: Aseem Sarvapriya
474REG. NO: 16BIT0303
475CSE1007 – JAVA PROGRAMMING
476ASSIGNMENT-2
477Question 1: A hash algorithm uses rotation and fold shift methods to compute the address at which the
478user input has to be stored. Define a static method to perform rotation of the data by moving the least
479significant digit to the most significant bit position. Also define a nonstatic method to perform fold shift
480by dividing the rotated data into segments of length 2 and then add all the segments to get the hash
481address. If the sum has more than 2 digits, delete the most significant digit and the resulting number is
482the address. Invoke these methods from main( ) method. Eg., If the data is 112286, after rotation it
483should be 611228 and after fold shift it should be 61 + 12 + 28=101 =01 (after deleting the most
484significant digit).
485CODE:
486class Hash
487{
488public static void main(String args[])
489{
490String check = "112286";
491String rotated = rotate(check);
492Hash h = new Hash();
493h.foldshift(rotated);
494}
495public static String rotate(String inp){
496char array[] = inp.toCharArray();
497char temp = '\0';
498for(int i=(array.length-1);i>=0;i--)
499{
500if(i==(array.length-1))
501{
502temp = array[i];
503array[i]=array[i-1];
504continue;
505}
506if(i==0)
507{
508array[i]=temp;
509break;
510}
511array[i]=array[i-1];
512}
513String out = String.valueOf(array);
514System.out.println(out);
515return out;
516}
517void foldshift(String inp){
518char[] arr = inp.toCharArray();
519int sum = 0;
520for(int i=0;i<arr.length;i=i+2){
521String temp = "";
522temp = temp + arr[i] + arr[i+1];
523sum += Integer.valueOf(temp);
524}
525if(sum>99){
526String out = String.valueOf(sum);
527out = out.substring(1,out.length());
528System.out.println(out);
529}
530else{
531System.out.println(sum);
532}
533}
534}
535OUTPUT:
536Question 2: Consider a Java program containing a statement to invoke format( ) method for displaying
537the output. Write a program to verify the syntax correctness of the statement by checking for the
538following.
539- The number of format specifiers and arguments should match.
540- Datatype of the arguments should match the format specifiers used.
541For example, if the input is similar to any of the three statements given below, the output should be
542“correct syntax†for the first two statements and it should be “wrong syntax†for the last statement.
543i) System.out.format("sum is %d"+" avg is %f ", a,b);
544ii) System.out.format(" name is %s"+"sum is %d avg is %f ", s,a,b);
545iii) System.out.format("sum is %d"+" avg is %f ", b,a);
546Assume you have a 2D String array storing all the variables used in the program and their datatypes as
547follows.
548CODE:
549class SyntaxCheck
550{
551public static void main(String args[])
552{
553SyntaxCheck sc = new SyntaxCheck();
554String[][] datatypes =
555{{"a","b","s","x"},{"int","float","String","int"}};
556String inp1 = "System.out.format(\"sum is %d\"+\" avg is %f \",a,b)";
557String inp2 = "System.out.format(\" name is %s\"+\"sum is %d avg is %f
558\",s,a,b)";
559String inp3 = "System.out.format(\"sum is %d\"+\" avg is %f \",b,a)";
560sc.syntaxcheck(inp1,datatypes);
561sc.syntaxcheck(inp2,datatypes);
562sc.syntaxcheck(inp3,datatypes);
563}
564void syntaxcheck(String input,String[][] datatypes)
565{
566String[] split = input.split(",");
567int index = 0;
568int flag = 1;
569for(int i=1;i<split.length;i++)
570{
571index = input.indexOf("%",index>0?index+1:0);
572String var = split[i];
573String datatype = "";
574for(int j=0;j<datatypes[0].length;j++)
575{
576if (datatypes[0][j].equals(var))
577{
578datatype = datatypes[1][j];
579}
580}
581if(datatype.equals("int"))
582{
583if(input.charAt(index+1)=='d')
584{
585continue;
586}
587else
588{
589flag = 0;
590System.out.println("Wrong Syntax");
591break;
592}
593}
594if(datatype.equals("float"))
595{
596if(input.charAt(index+1)=='f')
597{
598continue;
599}
600else
601{
602flag = 0;
603System.out.println("Wrong Syntax");
604break;
605}
606}
607if(datatype.equals("String"))
608{
609if(input.charAt(index+1)=='s')
610{
611continue;
612}
613else
614{
615flag = 0;
616System.out.println("Wrong Syntax");
617break;
618}
619}
620}
621if(flag==1)
622{
623System.out.println("Correct Syntax");
624}
625}
626}
627OUTPUT:
628Question 3: A training center conducts a total of 7 tests for its students. Students are allowed to skip few
629tests. Let there be 25 students in the batch. So in the main class for every student, read the number of
630tests taken and the marks scored in each test. A class ‘TestDetails’ should be defined with a 2D array of
631float type to store the marks of all the students. Define a method ‘storeMarks()’ that will receive the
632following details for every student from the main class and create in the 2D array, those many columns
633equal to the number of tests, so as to store the marks. There is no need to store the number of tests.
634Define another method ‘displayMarks()’ to print the details.
635Also the training centre wishes to keep those students in notice period who have taken < 3 tests and
636those who have not scored ≥ 50 in at least 3 tests. Derive another class ‘NoticePeriod’ from ‘TestDetails’
637that includes a method to count and print the number of students in bench. Also it should print the ID of
638those students assuming the row index of the array to be their ID. While checking do not proceed to
639check the marks in all tests, if the student has already scored more than 50 in 3 tests. Instantiate this
640class from the main class and do the required processing.
641CODE:
642import java.util.*;
643class TrainingCenter
644{
645public static void main(String args[])
646{
647int tests = 7;
648int batchStrength = 25;
649NoticePeriod td = new NoticePeriod();
650Scanner sc = new Scanner(System.in);
651for(int i=0;i<25;i++)
652{
653System.out.println("Input no of tests taken for student:
654"+(i+1));
655int testTaken = sc.nextInt();
656float[] mark = new float[testTaken];
657for(int j=0;j<testTaken;j++)
658{
659System.out.println("Input marks for student: "+(i+1)+" in
660test: "+(j+1));
661mark[j] = sc.nextFloat();
662}
663td.storeMarks(i,testTaken,mark);
664}
665td.displayMarks();
666td.noticePeriodStudents();
667}
668}
669class TestDetails
670{
671float[][] details = new float[25][];
672void storeMarks(int studentId,int testTaken,float[] mark)
673{
674details[studentId] = new float[testTaken];
675System.arraycopy(mark,0,details[studentId],0,testTaken);
676}
677void displayMarks()
678{
679for(int i=0;i<25;i++)
680{
681System.out.println("Marks for student: "+(i+1));
682for(int j=0;j<details[i].length;j++)
683{
684System.out.print("Marks in test: "+(j+1)+" is:
685"+details[i][j]);
686}
687System.out.println("");
688}
689}
690}
691class NoticePeriod extends TestDetails{ void noticePeriodStudents()
692{
693int count=0;
694String ids = "";
695for(int i=0;i<25;i++)
696{
697if(details[i].length<3)
698{
699count++; ids = ids + i;
700continue;
701}
702else
703{
704int greaterfiftymarks = 0;
705for(int j=0;j<details[i].length;j++)
706{
707if(details[i][j]>=50)
708{
709greaterfiftymarks++;
710if(greaterfiftymarks==3)
711{
712continue;
713}
714}
715else if(j==(details[i].length-1))
716{
717count++;
718ids = ids + i;
719}
720}
721}
722}
723System.out.println("No. of students in bench: "+ count);
724System.out.println("IDs of students in bench: "+ ids);
725}
726}
727OUTPUT:
728Question 4: Create an inheritance hierarchy in java using following information given below that a bank
729might use to represent customers’ bank accounts.
730Base class Account should include one data member of type double to represent account balance. The
731class should provide constructor that receives an initial balance and uses it to initialize the data
732member.The constructor should validate the initial balance to ensure that it is greater than or equal to
7330.If not the balance is set to 0.0 and the constructor should display an error message,indicating that the
734initial balance was invalid. The class also provides three member functions credit, debit(debit amount
735should not exceed the account balance) and enquiry.Derived class SavingsAccount should inherit the
736functionality of an Account, but also include data member of type double indicating the interest rate
737assigned to the Account.
738SavingsAccount constructor should receive the initial balance, as well as an initial value for
739SavingsAccount’s interest rate. SavingsAccount should provide public member function calculateInterest
740that returns double indicating the amount of interest earned by an account.The method calculateInterest
741should determine this amount by multiplying the interest rate by the account balance.SavingsAccount
742function should inherit member functions credit,debit and enquiry without redefining them. Derived class
743CheckingAccount should inherit the functionality of an Account, but also include data member of type
744double that represents the fee charged per transaction. CheckingAccount constructor should receive the
745initial balance, as well as parameter indicating fee amount. class CheckingAccount should redefine credit
746and debit function so that they subtract the fee from account balance whenever either transaction is
747performed. CheckingAccount’s debit function should charge a fee only if the money is actually withdrawn
748(debit amount should not exceed the account balance).After defining the class hierarchy, write program
749that creates object of each class and tests their member functions. Add interest to SavingAccount object
750by first invoking its calculateInterest function, then passing the returned interest amount to object’s credit
751function.
752CODE:
753import java.util.*;
754class Account
755{
756double balance;
757Account(double initbal)
758{
759if(initbal<0)
760{
761System.out.println("Invalid initial balance");
762}
763else
764{
765balance = initbal;
766}
767}
768void credit(double value)
769{
770balance+=value;
771System.out.println("Credit Successful!!");
772System.out.println("New Balance: "+ balance);
773}
774void debit(double value)
775{
776 if(value>balance)
777 {
778 System.out.println("Insufficient Funds!!");
779 }
780 else
781 {
782 balance-=value;
783 System.out.println("Debit Successful");
784 System.out.println("New Balance: "+ balance);
785 }
786}
787void enquiry()
788{
789 System.out.println("Current balance: "+balance);
790}
791}
792class SavingsAccount extends Account
793{
794 double interestRate;
795 SavingsAccount(double initbal,double ir)
796 {
797 super(initbal);
798 interestRate = ir;
799 }
800 public double calculateInterest()
801 {
802 double interest = balance*interestRate;
803 return interest;
804 }
805}
806class CheckingAccount extends Account
807{
808 double fee;
809 CheckingAccount(double initbal,double ifee)
810 {
811 super(initbal);
812 fee = ifee;
813 }
814 void credit(double value)
815 {
816 balance+=value;
817 balance-=fee;
818 System.out.println("Credit Successful!!");
819 System.out.println("New Balance: "+ balance);
820 }
821 void debit(double value)
822 {
823 if((value+fee)>balance)
824 {
825 System.out.println("Insufficient Funds!!");
826 }
827 else
828 {
829 balance-=(value+fee);
830 System.out.println("Debit Successful");
831 System.out.println("New Balance: "+ balance);
832 }
833 }
834}
835class Transactions
836{
837 public static void main(String args[])
838 {
839 Account ac = new Account(10);
840 SavingsAccount sac = new SavingsAccount(10,0.5);
841 CheckingAccount cac = new CheckingAccount(10,0.2);
842 Scanner sc = new Scanner(System.in);
843 double value;
844 boolean outer=true;
845 while(outer)
846 {
847 System.out.println(" Choose account: \n 1. Simple Account 2. Savings
848Account 3. Checking Account 4. Exit");
849 int choice = sc.nextInt();
850 boolean inner = true;
851 switch(choice)
852 {
853 case 1: while(inner)
854 {
855 System.out.println(" Choose operation: \n 1. Credit 2. Debit
8563. Enquiry 4. Exit");
857 int choiceop = sc.nextInt();
858 switch(choiceop)
859 {
860 case 1:
861 System.out.println("Insert amount: ");
862 value = sc.nextDouble();
863 ac.credit(value);
864 break;
865 case 2:
866 System.out.println("Insert amount: ");
867 value = sc.nextDouble();
868 ac.debit(value);
869 break;
870 case 3:
871 ac.enquiry();
872 break;
873 case 4:
874 inner = false;
875 break;
876 }
877 }
878 break;
879 case 2:
880 while(inner)
881 {
882 System.out.println(" Choose operation: \n 1. Credit 2. Debit
8833. Enquiry 4.Add Interest 5. Exit");
884 int choiceop = sc.nextInt();
885 switch(choiceop)
886 {
887 case 1:
888 System.out.println("Insert amount: ");
889 value = sc.nextDouble();
890 sac.credit(value);
891 break;
892 case 2:
893 System.out.println("Insert amount: ");
894 value = sc.nextDouble();
895 sac.debit(value);
896 break;
897 case 3:
898 sac.enquiry();
899 break;
900 case 4:
901 double interest = sac.calculateInterest();
902 sac.credit(interest);
903 break;
904 case 5:
905 inner = false;
906 break;
907 }
908 }
909 break;
910 case 3:
911 while(inner)
912 {
913 System.out.println(" Choose operation: \n 1. Credit 2. Debit
9143. Enquiry 4. Exit");
915 int choiceop = sc.nextInt();
916 switch(choiceop)
917 {
918 case 1:
919 System.out.println("Insert amount: ");
920 value = sc.nextDouble();
921 cac.credit(value);
922 break;
923 case 2:
924 System.out.println("Insert amount: ");
925 value = sc.nextDouble();
926 cac.debit(value);
927 break;
928 case 3:
929 cac.enquiry();
930 break;
931 case 4:
932 inner = false;
933 break;
934 }
935 }
936 break;
937 case 4:
938 outer = false;
939 break;
940 }
941 }
942 }
943}
944
945OUTPUT:
946Question 5: The interface GCD contains an abstract method computeGCD(int num1, int num2). Class
947APPROACH1 implements the interface by following Euclid’s algorithm and class APPROACH2 implements
948the interface by listing all the factors (need not be prime factors) of the two numbers and choosing the
949highest common factor. Write a Java program to do the above said operations.
950CODE:
951interface GCD
952{
953void computeGCD(int num1,int num2);
954}
955class APPORACH1 implements GCD
956{
957public void computeGCD(int num1,int num2)
958{
959int dividend=num1>=num2?num1:num2;
960int divisor=num1<=num2?num1:num2;
961while(divisor!=0)
962{
963int remainder=dividend%divisor;
964dividend=divisor;
965divisor=remainder;
966}
967System.out.println(dividend);
968}
969}
970class APPORACH2 implements GCD
971{
972public void computeGCD(int num1,int num2)
973{
974if (num1>num2)
975{
976int g=num1;
977num1=num2;
978num2=g;
979}
980int n=1;
981for (int i=2;i<=num1 ;i++ )
982{
983if (num1%i==0 && num2%i==0)
984{
985num1=num1/i;
986num2=num2/i;
987n=n*i;
988}
989}
990System.out.println(n);
991}
992}
993class TestInterface
994{
995public static void main(String[] args)
996{
997GCD euclid=new APPORACH1();
998euclid.computeGCD(100,600);
999GCD factors=new APPORACH2();
1000factors.computeGCD(50,70);
1001}
1002}
1003OUTPUT:
1004NAME: Aseem Sarvapriya
1005REG. NO: 16BIT0303
1006CSE1007 – JAVA PROGRAMMING
1007ASSIGNMENT-3
1008PACKAGE
1009Question 1:
1010Write a program to demonstrate the knowledge of students in working with user-defined
1011packages and sub-packages. E.g., Within the package named ‘primespackage’, define a class
1012Primes which includes a method checkForPrime() for checking if the given number is prime or
1013not. Define another class named TwinPrimes outside of this package which will display all the
1014pairs of prime numbers whose difference is 2. (Eg, within the range 1 to 10, all possible twin
1015prime numbers are (3,5), (5,7)). The TwinPrimes class should make use of the checkForPrime()
1016method in the Primes class.
1017CODE:
1018Primes.java
1019package primespackage;
1020public class Primes{
1021public boolean checkForPrime(int n){
1022boolean flag = true;
1023for(int i=2;i<=n/2;i++){
1024if(n%i==0){
1025flag = false;
1026}
1027}
1028return flag;
1029}
1030}
1031TwinPrimes.java
1032package twinPrimes;
1033import java.util.*;
1034import primespackage.*;
1035class TwinPrimes
1036{
1037Primes pr = new Primes();
1038int rangeMin;
1039int rangeMax;
1040TwinPrimes(int min,int max)
1041{
1042rangeMin = min;
1043rangeMax = max;
1044}
1045void twinPrimes()
1046{
1047System.out.println("Twin Prime Numbers are: ");
1048for(int i=rangeMin;i<rangeMax;i++){
1049if(!pr.checkForPrime(i))
1050{
1051continue;
1052}
1053for(int j=i+1;j<=rangeMax;j++)
1054{
1055if(!pr.checkForPrime(j))
1056{
1057continue;
1058}
1059else if(Math.abs(i-j)==2)
1060{
1061System.out.println("("+i+","+j+")");
1062}
1063}
1064}
1065}
1066public static void main(String args[])
1067{
1068TwinPrimes tp = new TwinPrimes(1,50);
1069tp.twinPrimes();
1070}
1071}
1072OUTPUT:
1073EXCEPTION HANDLING
1074Question 2: Read the Register Number and Mobile Number of a student. If the Register Number
1075does not contain exactly 9 characters or if the Mobile Number does not contain exactly 10
1076characters, throw an IllegalArgumentException. If the Mobile Number contains any character
1077other than a digit, raise a NumberFormatException. If the Register Number contains any
1078character other than digits and alphabets, throw a NoSuchElementException. If they are valid,
1079print the message ‘valid’ else ‘invalid’.
1080CODE:
1081import java.util.*;
1082import java.lang.*;
1083class Check
1084{
1085public static void main (String args[])
1086{
1087Scanner s = new Scanner(System.in);
1088System.out.println("Enter Registration Number");
1089String reg_no = s.next();
1090System.out.println("Enter Mobile Number");
1091String mob_no = s.next();
1092int flag = 0;
1093try
1094{
1095if(reg_no.length() != 9 && mob_no.length() != 10)
1096throw new IllegalArgumentException("Length wrong");
1097}
1098catch (IllegalArgumentException e)
1099{
1100System.out.println(e); flag = 1;
1101}
1102String regex1 = "[0-9]+";
1103String regex2 = "^[A-Za-z0-9]+$";
1104try
1105{
1106if(!reg_no.matches(regex2))
1107throw new NoSuchElementException("Registration No Wrong");
1108}
1109catch (NoSuchElementException e2)
1110{
1111System.out.println(e2); flag = 1;
1112}
1113try
1114{
1115if(!mob_no.matches(regex1))
1116throw new NumberFormatException("Contains character other
1117than digits");
1118}
1119catch (NumberFormatException e1)
1120{
1121System.out.println(e1);
1122flag = 1;
1123}
1124if(flag == 0)
1125{
1126System.out.println("Valid");
1127}
1128else
1129{
1130System.out.println("Invalid");
1131}
1132}
1133}
1134OUTPUT:
1135Question 3: A bag contains balls of 4 different colors- red, green, blue and yellow. Simulate
1136picking up a ball at random for ten times. If the same colored ball is picked more than thrice,
1137throw SameColorBallException and proceed with the simulation once again. After 10 valid picks,
1138print the number of balls chosen from each of these colors.
1139CODE:
1140import java.util.*;
1141import java.lang.*;
1142class BallColors
1143{
1144public static void main(String args[])
1145{
1146String[] colors = {"red","green","blue","yellow"};
1147int i=0;
1148int red_c=0,green_c=0,blue_c=0,yellow_c=0;
1149Random random = new Random();
1150while(i<10){
1151int ind = random.nextInt(4);
1152if (ind == 0)
1153{
1154red_c++;
1155}
1156else if (ind == 1)
1157{
1158green_c++;
1159}
1160else if (ind == 2)
1161{
1162blue_c++;
1163}
1164else if (ind == 3)
1165{
1166yellow_c++;
1167}
1168try
1169{
1170if(red_c>3 || yellow_c>3 || blue_c>3 || yellow_c>3)
1171{
1172red_c=0;
1173green_c=0;
1174blue_c=0;
1175yellow_c=0;
1176i=0;
1177throw new Exception("Same Color Ball Exception");
1178}
1179else
1180{
1181i++;
1182}
1183}
1184catch (Exception e)
1185{
1186System.out.println(e);
1187}
1188}
1189System.out.println("No of Balls Chosen: ");
1190System.out.println("Red: "+ red_c);
1191System.out.println("Red: "+ green_c);
1192System.out.println("Red: "+ blue_c);
1193System.out.println("Red: "+ yellow_c);
1194}
1195}
1196OUTPUT:
1197Multithreading
1198Question 4:
1199CODE:
1200class MultiThreading1 extends Thread
1201{
1202int[][] marksCount = {{1,2,3,4,5,6,7,8,9,10},{3,4,17,8,23,10,4,6,5,2}};
1203int fxsum;
1204public synchronized void run()
1205{
1206for(int j=0;j<marksCount[0].length;j++)
1207{
1208fxsum += (marksCount[1][j]*marksCount[0][j]);
1209}
1210}
1211}
1212class MultiThreading2 extends Thread
1213{
1214int[][] marksCount = {{1,2,3,4,5,6,7,8,9,10},{3,4,17,8,23,10,4,6,5,2}};
1215int fsum;
1216public synchronized void run()
1217{
1218for(int j=0;j<marksCount[0].length;j++)
1219{
1220fsum += marksCount[1][j];
1221}
1222}
1223}
1224class MultiThreading
1225{
1226public static void main(String args[])
1227{
1228MultiThreading1 m1 = new MultiThreading1();
1229MultiThreading2 m2 = new MultiThreading2();
1230m1.start();
1231m2.start();
1232while(m1.isAlive() || m2.isAlive())
1233{
1234continue;
1235}
1236double mean = (m1.fxsum/m2.fsum);
1237System.out.println("Mean is: "+ mean);
1238}
1239}
1240
1241OUTPUT:
1242NAME: Aseem Sarvapriya
1243REG. NO: 16BIT0303
1244CSE1007 – JAVA PROGRAMMING
1245ASSIGNMENT-4 & 5
1246Assignment-4
1247Question 1.Write a program to demonstrate the knowledge of students in multithreading. Eg.,
1248Three students A, B and C of B.Tech- II year contest for the PR election. With the total strength
1249of 240 students in II year, simulate the vote casting by generating 240 random numbers (1 for
1250student A, 2 for B and 3 for C) and store them in an array. Create four threads to equally share
1251the task of counting the number of votes cast for all the three candidates. Use synchronized
1252method or synchronized block to update the three count variables. The main thread should
1253receive the final vote count for all three contestants and hence decide the PR based on the
1254values received.
1255Vote.java
1256package elections;
1257import java.util.Random;
1258import java.util.Vector;
1259public class Vote extends Thread{
1260Random rand = new Random();
1261int max = 750;
1262int min = 100;
1263int v, s;
1264Vector vec;
1265public Vote(int v, Vector vec)
1266{
1267this.v = v;
1268this.vec = vec;
1269}
1270public void run() {
1271try
1272{
1273while(vec.size() < 240) { System.out.println("Thread " +
1274this.getId() + " is Voting");
1275vec.add(v);
1276s = rand.nextInt((max - min) + 1) + min;
1277System.out.println("Thread " + this.getId() + " is sleeping for " + s);
1278Thread.sleep(s); }
1279}
1280catch(InterruptedException e)
1281{
1282System.out.println("Voting Exception: " + e);
1283}
1284}
1285}
1286Count.java
1287package elections;
1288import java.util.Vector;
1289public class count extends Thread
1290{
1291Vector vec;
1292int k, i;
1293public int count = 0;
1294public count(int k, Vector vec)
1295{
1296this.k = k;
1297this.vec = vec;
1298}
1299public void run()
1300{
1301try
1302{
1303for(i = 0; i < vec.capacity(); i++)
1304{
1305if(vec.elementAt(i).equals(k))
1306count++;
1307}
1308}
1309catch(Exception e)
1310{ System.out.println(e);
1311}
1312}
1313}
1314MultiThreadVote.java
1315package elections;
1316import elections.Vote;
1317import elections.Count;
1318import java.util.Vector;
1319public class MultiThreadVote {
1320public static void main(String[] args) {
1321Vector votevec = new Vector(240);
1322Vote a = new Vote(1, votevec);
1323a.start();
1324Vote b = new Vote(2, votevec);
1325b.start();
1326Vote c = new Vote(3, votevec);
1327c.start();
1328try{
1329a.join();
1330b.join();
1331c.join();
1332System.out.println("Voting has ended!");
1333}catch(Exception e){System.out.println(e);}
1334Count ac = new Count(1, votevec);
1335Count bc = new Count(2, votevec);
1336Count cc = new Count(3, votevec);
1337ac.start();
1338bc.start();
1339cc.start();
1340try{
1341ac.join();
1342bc.join();
1343cc.join();
1344System.out.println("Counting has ended!");
1345}catch(Exception e){System.out.println(e);}
1346int av = ac.Count;
1347int bv = bc.Count;
1348int cv = cc.Count;
1349System.out.println("elections.Vote Vector:" + "\n" + votevec);
1350System.out.println(av + " votes for A");
1351System.out.println(bv + " votes for B");
1352System.out.println(cv + " votes for C");
1353if(av >= bv && av >= cv){
1354if(av == bv || av == cv)
1355System.out.println("Tie in elections!");
1356else
1357System.out.println("A has won the elections!");
1358}
1359else if(bv >= av && bv >= cv){
1360if(av == bv || bv == cv)
1361System.out.println("Tie in elections!");
1362else
1363System.out.println("B has won the elections!");
1364}
1365else if(cv >= av && cv >= bv){
1366if(cv == bv || cv == av)
1367System.out.println("Tie in elections!");
1368else
1369System.out.println("C has won the elections!");
1370}
1371}
1372}
1373OUTPUT
13742.Write a program that takes a file name and a search string from the user. If the search string
1375occurs in the file, then it counts the number of occurrences of the string. ( Assume that search
1376pattern can exist more than two times in a line ).
1377CODE:
1378import java.util.*;
1379import java.io.*;
1380class Search
1381{
1382public static void main(String args[])
1383{
1384Scanner in= new Scanner(System.in);
1385try
1386{
1387System.out.print("Enter the File name and search word: ");
1388String filename= in.nextLine();
1389String word= in.nextLine();
1390FileReader fr= new FileReader(filename);
1391int line=fr.read();
1392int count=0;
1393String s="";
1394while(line!=-1)
1395{
1396s+=(char)line;
1397line=fr.read();
1398}
1399String[] ar= s.split(" ");
1400for(int i=0;i<ar.length;i++)
1401{
1402if(word.equals(ar[i]))
1403{
1404count++;
1405}
1406}
1407fr.close();
1408System.out.println("The no of occurances of String "+word+" is: "+count);
1409}
1410catch(Exception e)
1411{
1412e.printStackTrace();
1413}
1414}
1415}
1416OUTPUT:
1417Question 3. Write a program to demonstrate the knowledge of students in File handling. Eg.,
1418Define a class ‘Donor’ to store the below mentioned details of a blood donor. Name, age,
1419Address, Contact number, blood group, date of last donation Create ‘n’ objects of this class for
1420all the regular donors at Vellore. Write these objects to a file. Read these objects from the file
1421and display only those donors’ details whose blood group is ‘A+ve’ and had not donated for
1422the recent six months.
1423CODE:
1424import java.util.*;
1425import java.text.ParseException;
1426import java.text.SimpleDateFormat;
1427import java.time.*;
1428import java.io.*;
1429import java.io.FileReader;
1430public class Last{
1431public static void main(String a[])throws IOException{
1432FileWriter fw=new FileWriter("input.txt");
1433String name;
1434int age;
1435String address;
1436String num;
1437String bg;
1438String ld;
1439SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
1440Date d1=null;
1441Date date2=null;
1442Scanner scan=new Scanner(System.in);
1443for(int i=0;i<2;i++){
1444String in="";
1445System.out.println("name");
1446name=scan.nextLine();
1447System.out.println("age");
1448age=scan.nextInt();
1449scan.nextLine(); // skip the newline character
1450System.out.println("address");
1451address=scan.nextLine();
1452System.out.println("number");
1453num=scan.nextLine();
1454System.out.println("bg");
1455bg=scan.nextLine();
1456System.out.println("ld");
1457ld=scan.nextLine();
1458in="name: "+name+" age: "+age+" address: "+address+" num: "+num+"
1459bloodgroup: "+bg+" lastdate: "+ld+"\n";
1460fw.write(in);
1461}
1462fw.close();
1463FileReader fr=new FileReader("input.txt");
1464 String s="";
1465 int i;
1466 while((i=fr.read())!=-1)
1467s+=(char)i;
1468 fr.close();
1469String arr[]=s.split("\n");
1470for(int k=0;k<arr.length;k++){
1471String ar[]=arr[k].split(" ");
1472String date=ar[11];
1473try {
1474 //Parsing the String
1475 d1 = dateFormat.parse(date);
1476 date2 = dateFormat.parse("21-02-2019");
1477} catch (ParseException e) {
1478 // TODO Auto-generated catch block
1479 e.printStackTrace();
1480}
1481long d=date2.getTime()-d1.getTime();
1482d=((((d/60)/60)/24)/1000)/30;
1483if(ar[9].equals("A+")&d>6) //condition of A+ and 6 months
1484System.out.println(arr[k]);
1485}
1486}
1487}
1488Output:
1489Assignment 5
1490Question 1: Java Program to Replace First Letter of Every Word with Capital Letter.
1491CODE:
1492import java.io.*;
1493import java.lang.*;
1494class First{
1495public static void main(String[] args){
1496String s="";
1497try{
1498FileWriter fw=new FileWriter("C:\\Users\\admin\\Desktop\\first.txt");
1499fw.write("my name is aseem sarvapriya");
1500fw.close();
1501}
1502catch(Exception e){
1503System.out.println(e);
1504}
1505try{
1506FileReader fr=new FileReader("C:\\Users\\admin\\Desktop\\first.txt");
1507int i=fr.read();
1508while(i!=-1){
1509char d=(char)i;
1510s=s+d;
1511i=fr.read();
1512}
1513fr.close();
1514}
1515catch(Exception e){
1516e.printStackTrace();
1517}
1518String arr[]=s.split("\\ ");
1519for(int i=0;i<arr.length;i++){
1520arr[i]=Character.toUpperCase(arr[i].charAt(0))+arr[i].substring(1);
1521System.out.print(arr[i]+" ");
1522}
1523System.out.println();
1524}
1525}
1526OUTPUT:
1527Question 2: Java Program to Reverse the Contents of a File and Print it.
1528CODE:
1529import java.io.*;
1530class Reverse{
1531public static void main(String[] args){
1532String s="";
1533try{
1534FileWriter fw=new FileWriter("C:\\Users\\admin\\Desktop\\reverse.txt");
1535fw.write("My name is Aseem Sarvapriya");
1536fw.close();
1537}
1538catch(Exception e){
1539System.out.println("Success....");
1540}
1541try{
1542FileReader fr=new FileReader("/C:\\Users\\admin\\Desktop\\reverse.txt");
1543int i=fr.read();
1544while(i!=-1){
1545char d=(char)i;
1546s=s+d;
1547i=fr.read();
1548}
1549fr.close();
1550}
1551catch(Exception e){
1552e.printStackTrace();
1553}
1554String arr[]=s.split("");
1555for(int i=arr.length-1;i>=0;i--){
1556System.out.print(arr[i]);
1557}
1558System.out.println();
1559}
1560}
1561OUTPUT:
1562Question 3: Java Program to Update Details of Employee Using Files.
1563CODE:
1564import java.io.*;
1565import java.nio.file.Files;
1566import java.nio.file.NoSuchFileException;
1567import java.nio.file.Paths;
1568import java.text.ParseException;
1569import java.util.Scanner;
1570public class Emp {
1571String name,addr,contact;
1572public static void main(String[] args) throws
1573IOException{
1574int n, i;
1575// delete existing file first
1576try{
1577Files.deleteIfExists(Paths.get("hello.txt"));
1578}
1579catch(NoSuchFileException e)
1580{
1581System.out.println("No such file/directory exists");
1582}
1583catch(IOException e)
1584{
1585System.out.println("Invalid permissions.");
1586}
1587System.out.println("Deletion successful.");
1588Scanner sc = new Scanner(System.in);
1589System.out.print("Enter number of Employees: ");
1590n = sc.nextInt();
1591sc.nextLine();
1592Emp arr[] = new Emp[n];
1593// creating array of n Employees
1594ByteArrayOutputStream outputstream = new
1595ByteArrayOutputStream();
1596FileOutputStream fos = new
1597FileOutputStream("hello.txt"); // creating file to write to
1598for(i = 0; i < n; i++){
1599arr[i] = new Emp();
1600// initializing new Employee
1601//taking input from user
1602System.out.print("Name: ");
1603arr[i].name = sc.nextLine();
1604System.out.print("Address: ");
1605arr[i].addr = sc.nextLine();
1606System.out.print("Contact: ");
1607arr[i].contact = sc.nextLine();
1608// concatenating all properties in employee object
1609// and converting to a byte stream
1610outputstream.write(("Employee " + (i+1) + "\n").getBytes());
1611outputstream.write("----------------\n".getBytes());
1612outputstream.write("Name: ".getBytes());
1613outputstream.write(arr[i].name.getBytes());
1614outputstream.write("\n".getBytes());
1615outputstream.write("Address: ".getBytes());
1616outputstream.write(arr[i].addr.getBytes());
1617outputstream.write("\n".getBytes());
1618outputstream.write("Contact: ".getBytes());
1619outputstream.write(arr[i].contact.getBytes());
1620outputstream.write("\n".getBytes());
1621}
1622byte c[] = outputstream.toByteArray();
1623fos.write(c);
1624fos.close();
1625ByteArrayOutputStream outputstream1 = new ByteArrayOutputStream();
1626FileOutputStream fos1 = new
1627FileOutputStream("hello.txt");
1628System.out.print("Enter the name employee to modify:");
1629String nam= sc.nextLine();
1630for(i=0;i<n;i++)
1631{
1632if(arr[i].name.equals(nam))
1633{
1634System.out.print("Enter the new Address and contact: ");
1635arr[i].addr=sc.nextLine();
1636arr[i].contact=sc.nextLine();
1637}
1638try{
1639Files.deleteIfExists(Paths.get("hello.txt"));
1640}
1641catch(NoSuchFileException e)
1642{
1643System.out.println("No such file/directory exists");
1644}
1645outputstream1.write(("Employee " + (i+1) +
1646"\n").getBytes());
1647outputstream1.write("----------------\n".getBytes());
1648outputstream1.write("Name: ".getBytes());
1649outputstream1.write(arr[i].name.getBytes());
1650outputstream1.write("\n".getBytes());
1651outputstream1.write("Address: ".getBytes());
1652outputstream1.write(arr[i].addr.getBytes());
1653outputstream1.write("\n".getBytes());
1654outputstream1.write("Contact: ".getBytes());
1655outputstream1.write(arr[i].contact.getBytes());
1656outputstream1.write("\n".getBytes());
1657}
1658// create a byte array to be written
1659byte d[] = outputstream1.toByteArray();
1660fos1.write(d);
1661// writing byte array to file
1662fos1.close();
1663}
1664}
1665Question 4: Java Program to Convert the Content of File to LowerCase.
1666CODE:
1667import java.io.*;
1668import java.lang.*;
1669import java.util.*;
1670class Convert{
1671public static void main(String[] args){
1672Scanner sc= new Scanner(System.in);
1673System.out.println("Enter a sentence in upper case:");
1674String l=sc.nextLine();
1675String s="";
1676try{
1677FileWriter fw=new FileWriter("C:\\Users\\admin\\Desktop\\Convert.txt");
1678fw.write(l);
1679fw.close();
1680}
1681catch(Exception e){
1682System.out.println(e);
1683}
1684try{
1685FileReader fr=new FileReader("C:\\Users\\admin\\Desktop\\Convert.txt");
1686int i=fr.read();
1687while(i!=-1){
1688char d=(char)i;
1689s=s+d;
1690i=fr.read();
1691}
1692fr.close();
1693}
1694catch(Exception e){
1695e.printStackTrace();
1696}
1697System.out.println("Content of file in lower case :");
1698for(int i=0;i<s.length();i++){
1699System.out.print(Character.toLowerCase(s.charAt(i)));
1700}
1701System.out.println();
1702}
1703}
1704
1705OUTPUT:
1706Question 5: Java Program to Create and Count Number of Characters in a File.
1707CODE:
1708import java.io.*;
1709import java.lang.*;
1710import java.util.*;
1711class Noc{
1712public static void main(String[] args){
1713Scanner sc= new Scanner(System.in);
1714System.out.println("Enter a sentence: ");
1715String l=sc.nextLine();
1716String s="";
1717try{
1718FileWriter fw=new FileWriter("C:\\Users\\admin\\Desktop\\first.txt");
1719fw.write(l);
1720fw.close();
1721}
1722catch(Exception e){
1723System.out.println(e);
1724}
1725try{
1726FileReader fr=new FileReader("C:\\Users\\admin\\Desktop\\first.txt");
1727int i=fr.read();
1728while(i!=-1){
1729char d=(char)i;
1730s=s+d;
1731i=fr.read();
1732}
1733fr.close();
1734}
1735catch(Exception e){
1736e.printStackTrace();
1737}
1738String arr[]=s.split("");
1739int count=arr.length;
1740System.out.println("Number of Characters in File: :");
1741System.out.println(count);
1742}
1743}
1744OUTPUT:
1745Question 6. Java Program to Join Lines of Two given Files and Store them in a New file
1746CODE:
1747import java.io.*;
1748import java.lang.*;
1749import java.util.*;
1750class Join{
1751public static void main(String[] args) throws IOException{
1752Scanner sc= new Scanner(System.in);
1753System.out.println("Enter a sentence for file 1: ");
1754String l=sc.nextLine();
1755System.out.println("Enter a sentence for file 2: ");
1756String h=sc.nextLine();
1757String s1="";
1758String s2="";
1759String s3="";
1760FileWriter fw=new FileWriter("first.txt");
1761fw.write(l);
1762fw.close();
1763FileWriter fw2=new FileWriter("first2.txt");
1764fw2.write(h);
1765fw2.close();
1766FileReader fr=new FileReader("first.txt");
1767int i=fr.read();
1768while(i!=-1){
1769char d=(char)i;
1770s1=s1+d;
1771i=fr.read();
1772}
1773fr.close();
1774FileReader f2=new FileReader("first2.txt");
1775int j=f2.read();
1776while(j!=-1){
1777char v=(char)j;
1778s2=s2+v;
1779j=f2.read();
1780}
1781f2.close();
1782String q=s1+" "+s2;
1783FileWriter fw3=new FileWriter("final.txt");
1784fw3.write(q);
1785fw3.close();
1786FileReader f3=new FileReader("final.txt");
1787int y=f3.read();
1788while(y!=-1){
1789char g=(char)y;
1790s3=s3+g;
1791y=f3.read();
1792}
1793f3.close();
1794System.out.println("String after adding strings from file 1 and file 2: ");
1795System.out.println(s3);
1796}
1797}
1798OUTPUT:
1799Question 7. Java Program to Collect Statistics of a Source File like Total Lines, Total no. of Blank
1800Lines, Total no. of Lines Ending with Semicolon.
1801CODE:
1802import java.util.*;
1803import java.io.*;
1804class Statistics
1805{
1806public static void main(String args[])
1807{
1808try
1809{
1810BufferedReader ob= new BufferedReader(new FileReader("First.txt"));
1811String line=ob.readLine();
1812int no_of_lines=0,no_of_blanklines=0,no_of_semi=0;
1813while(line!=null)
1814{
1815no_of_lines++;
1816if(line.trim().isEmpty())
1817no_of_blanklines++;
1818if(line.endsWith(";"))
1819no_of_semi++;
1820line=ob.readLine();
1821}
1822ob.close();
1823System.out.println("Total no of lines: "+no_of_lines);
1824System.out.println("Total no of blank lines: "+no_of_blanklines);
1825System.out.println("Total no of lines ending with semicolon: "+no_of_semi);
1826}
1827catch(Exception e)
1828{
1829e.printStackTrace();
1830}
1831}
1832}
1833OUTPUT
1834NAME: Aseem Sarvapriya
1835REG. NO: 16BIT0303
1836Question 1: Find the largest number among three.
1837CODE:
1838import java.util.*;
1839public class Largest
1840{
1841public static void main(String[] args)
1842{
1843Scanner sc =new Scanner(System.in);
1844int n1= sc.nextInt();
1845int n2= sc.nextInt();
1846int n3= sc.nextInt();
1847if( n1 >= n2 && n1 >= n3)
1848 System.out.println(n1 + " is the largest number.");
1849 else if (n2 >= n1 && n2 >= n3)
1850 System.out.println(n2 + " is the largest number.");
1851 else
1852 System.out.println(n3 + " is the largest number.");
1853}
1854}
1855Question 2: Generate Fibonacci series:
1856CODE:
1857import java.util.*;
1858public class Fibonacci
1859{
1860public static void main(String[] args)
1861{
1862Scanner a=new Scanner(System.in);
1863int n= a.nextInt();
1864 int t1 = 0, t2 = 1;
1865 System.out.print("First " + n + " terms: ");
1866 for (int i = 1; i <= n; ++i)
1867 {
1868 System.out.print(t1 + " + ");
1869 int sum = t1 + t2;
1870 t1 = t2;
1871 t2 = sum;
1872 }
1873}
1874}
1875Question 3: Check if number is Armstrong.
1876CODE:
1877import java.util.*;
1878public class Armstrong
1879{
1880public static void main(String[] args)
1881{
1882int sum=0,n,a,temp;
1883Scanner s=new Scanner(System.in);
1884n=s.nextInt();
1885temp=n;
1886while(n>0)
1887{
1888a=n%10;
1889n=n/10;
1890sum=sum+(a*a*a);
1891}
1892 if(temp==sum)
1893 System.out.println("armstrong number");
1894 else
1895 System.out.println("Not armstrong number");
1896}
1897}
1898Question 4: Find first 50 prime numbers.
1899CODE:
1900public class Prime
1901{
1902 public static void main(String[] args)
1903 {
1904 int count = 0, max_count = 50, i;
1905 System.out.println("First "+max_count+" Prime Numbers:");
1906 for(int num=1; count<max_count; num++)
1907 {
1908 for(i=2; num%i != 0; i++);
1909 if(i == num)
1910 {
1911 System.out.print(" "+num);
1912 count++;
1913 }
1914 }
1915 }
1916}
1917Question 5: Find the k smallest and k largest element in an array.
1918CODE:
1919import java.util.*;
1920public class Knumber
1921{
1922public static void main(String[] args)
1923{
1924 Integer arr[] = new Integer[]{12, 3, 5, 7, 19};
1925 Arrays.sort(arr);
1926 int k1 = 2;
1927 System.out.println( "K'th smallest element is "+ arr[k1]);
1928 Arrays.sort(arr,Collections.reverseOrder());
1929 int k2 = 2;
1930 System.out.print( "K'th Largest element is "+ arr[k2]);
1931
1932}
1933}
1934Question 6: Sort the element in descending order.
1935CODE:
1936import java.util.*;
1937public class DescendingOrder
1938{
1939 public static void main(String[] args)
1940 {
1941 int n, temp;
1942 Integer arr[] = new Integer[]{12, 3, 5, 7, 19, 22, 40, 50};
1943 n=arr.length;
1944 for (int i = 0; i < n; i++)
1945 {
1946 for (int j = i + 1; j < n; j++)
1947 {
1948 if (arr[i] < arr[j])
1949 {
1950 temp = arr[i];
1951 arr[i] = arr[j];
1952 arr[j] = temp;
1953 }
1954 }
1955 }
1956 System.out.print("Descending Order:");
1957 for (int i = 0; i < n - 1; i++)
1958 {
1959 System.out.print(arr[i] + ",");
1960 }
1961 System.out.print(arr[n - 1]);
1962 }
1963}
1964Question 7: Write a program for matrix multiplication.
1965CODE:
1966class Matrixmultiplication
1967{
1968public static void main(String args[])
1969int a[][]={{1,2,3},{4,5,6},{7,8,9}};
1970int b[][]={{1,2,3},{4,5,6},{7,8,9}};
1971 int c[][]=new int[3][3];
1972 for(int i=0;i<3;i++)
1973 {
1974 for(int j=0;j<3;j++)
1975 {
1976 c[i][j]=0;
1977 for(int k=0;k<3;k++)
1978 {
1979 c[i][j]+=a[i][k]*b[k][j];
1980 }
1981 System.out.print(c[i][j]+" ");
1982 }
1983 System.out.println();
1984 }
1985}
1986}
1987Question 8: Write a program to find transpose of a matrix.
1988CODE:
1989class Transposematrix
1990{
1991 public static void main(String args[])
1992 {
1993int i, j;
1994int a[][]={{1,2,3},{4,5,6},{7,8,9}};
1995System.out.println("The above matrix after Transpose is ");
1996 for(i = 0; i < 3; i++)
1997 {
1998 for(j = 0; j < 3; j++)
1999 {
2000 System.out.print(a[j][i]+" ");
2001 }
2002 System.out.println(" ");
2003 }
2004 }
2005}
2006NAME: Aseem Sarvapriya
2007REG. NO: 16BIT0303
2008CSE1007 – JAVA PROGRAMMING
2009Servlet Programs
2010Q1. Create a table for students that contains student name register number
2011marks of 3 subjects. Write a servlet code to retrieve the student information
2012and compute the total and average of all these students and display in table
2013format
2014Code:
2015register.java
2016import java.io.*;
2017import java.sql.*;
2018import javax.servlet.ServletException;
2019import javax.servlet.http.*;
2020import com.mysql.jdbc.Driver;
2021import javax.servlet.ServletContext;
2022import javax.swing.JOptionPane;
2023public class register extends HttpServlet {
2024@Override
2025public void doPost(HttpServletRequest request, HttpServletResponse response)
2026 throws ServletException, IOException {
2027//response.setContentType("text/html");
2028PrintWriter out = response.getWriter();
2029//String n=request.getParameter("phone_number");
2030//String p=request.getParameter("name");
2031//String e=request.getParameter("psw");
2032//String c=request.getParameter("gender");
2033try{
2034Class.forName("com.mysql.jdbc.Driver");
2035Connection
2036con=DriverManager.getConnection("jdbc:mysql://localhost:3307/Java_DA","root","Aseem");
2037
2038System.out.println("*** Connect to the database ***");
2039String query="select * from student; ";
2040Statement smnt = con.createStatement();
2041//smnt.executeUpdate(query);
2042//ServletContext sc = getServletContext();
2043//sc.getRequestDispatcher("/2.html").forward(request, response);
2044 out.println("<!DOCTYPE html>");
2045 out.println("<html>");
2046 out.println("<head>");
2047 out.println("<title>You are registered</title>");
2048 out.println("</head>");
2049 out.println("<body>");
2050 out.println("<table border=1>");
2051 out.println("<tr>");
2052 out.println("<th>");
2053 out.println("Name");
2054 out.println("</th>");
2055 out.println("<th>");
2056 out.println("Reg_number");
2057 out.println("</th>");
2058 out.println("<th>");
2059 out.println("marks1");
2060 out.println("</th>");
2061 out.println("<th>");
2062 out.println("marks2");
2063 out.println("</th>");
2064 out.println("<th>");
2065 out.println("marks3");
2066 out.println("</th>");
2067 out.println("<th>");
2068 out.println("Total");
2069 out.println("</th>");
2070 out.println("<th>");
2071import java.io.*;
2072import java.sql.*;
2073import javax.servlet.ServletException;
2074import javax.servlet.http.*;
2075import com.mysql.jdbc.Driver;
2076import javax.servlet.ServletContext;
2077import javax.swing.JOptionPane;
2078
2079public class register extends HttpServlet {
2080@Override
2081public void doPost(HttpServletRequest request, HttpServletResponse response)
2082 throws ServletException, IOException {
2083
2084//response.setContentType("text/html");
2085PrintWriter out = response.getWriter();
2086
2087//String n=request.getParameter("phone_number");
2088//String p=request.getParameter("name");
2089//String e=request.getParameter("psw");
2090//String c=request.getParameter("gender");
2091
2092try{
2093Class.forName("com.mysql.jdbc.Driver");
2094Connection
2095con=DriverManager.getConnection("jdbc:mysql://localhost:3307/Java_DA","root","Aseem");
2096
2097System.out.println("*** Connect to the database ***");
2098String query="select * from employee where designation ='supervisor'; ";
2099String query2="select * from employee where designation !='supervisor';";
2100Statement smnt = con.createStatement();
2101//smnt.executeUpdate(query);
2102//ServletContext sc = getServletContext();
2103//sc.getRequestDispatcher("/2.html").forward(request, response);
2104 out.println("<!DOCTYPE html>");
2105 out.println("<html>");
2106 out.println("<head>");
2107 out.println("<title>You are registered</title>");
2108 out.println("</head>");
2109 out.println("<body>");
2110 out.println("<table border=1>");
2111 out.println("<tr>");
2112 out.println("<th>");
2113 out.println("EmpName");
2114 out.println("</th>");
2115 out.println("<th>");
2116 out.println("EmpId");
2117 out.println("</th>");
2118 out.println("<th>");
2119 out.println("Designation");
2120 out.println("</th>");
2121 out.println("<th>");
2122 out.println("Salary");
2123 out.println("</th>");
2124 out.println("</tr>");
2125 ResultSet rs = smnt.executeQuery(query);
2126while (rs.next()){
2127String name=rs.getString("empname");
2128String reg=rs.getString("empid");
2129String marks1=rs.getString("designation");
2130String marks2=rs.getString("salary");
2131 out.println("<tr>");
2132 out.println("<td>");
2133 out.println(name);
2134 out.println("</td>");
2135 out.println("<td>");
2136 out.println(reg);
2137 out.println("</td>");
2138 out.println("<td>");
2139 out.println(marks1);
2140 out.println("</td>");
2141 out.println("<td>");
2142 out.println(marks2);
2143 out.println("</td>");
2144 out.println("</tr>");}
2145 out.println("</table>");
2146 out.println("br");
2147 out.println("br");
2148
2149 out.println("<table border=1>");
2150 out.println("<tr>");
2151 out.println("<th>");
2152 out.println("Name");
2153 out.println("</th>");
2154 out.println("<th>");
2155 out.println("designation");
2156 out.println("</th>");
2157 out.println("</tr>");
2158 ResultSet rs1 = smnt.executeQuery(query);
2159while (rs1.next()){
2160String name=rs1.getString("empname");
2161String reg=rs1.getString("empid");
2162String marks1=rs1.getString("designation");
2163String marks2=rs1.getString("salary");
2164 out.println("<tr>");
2165 out.println("<td>");
2166 out.println(name);
2167 out.println("</td>");
2168out.println("<td>");
2169 out.println(marks1);
2170 out.println("</td>");
2171 out.println("</tr>");}
2172 out.println("</table>");
2173
2174 out.println("</body>");
2175 out.println("</html>");
2176//Visible= this.setVisible(false);
2177 // new menu().setVisible(true);
2178
2179//if(i>0)
2180//out.print("You are successfully registered...");
2181}catch (Exception e2) {System.out.println(e2);}
2182
2183out.close();
2184}
2185}
2186 out.println("Avg");
2187 out.println("</th>");
2188 out.println("</tr>");
2189 ResultSet rs = smnt.executeQuery(query);
2190while (rs.next()){
2191String name=rs.getString("name");
2192String reg=rs.getString("regnum");
2193String marks1=rs.getString("marks1");
2194String marks2=rs.getString("marks2");
2195String marks3=rs.getString("marks3");
2196int m1=Integer.parseInt(marks1);
2197int m2=Integer.parseInt(marks2);
2198int m3=Integer.parseInt(marks3);
2199int t=m1+m2+m3,a=((m1+m2+m3)/3);
2200 out.println("<tr>");
2201 out.println("<td>");
2202 out.println(name);
2203 out.println("</td>");
2204 out.println("<td>");
2205 out.println(reg);
2206 out.println("</td>");
2207 out.println("<td>");
2208 out.println(marks1);
2209 out.println("</td>");
2210 out.println("<td>");
2211 out.println(marks2);
2212 out.println("</td>");
2213 out.println("<td>");
2214 out.println(marks3);
2215 out.println("</td>");
2216 out.println("<td>");
2217 out.println(""+t);
2218 out.println("</td>");
2219 out.println("<td>");
2220 out.println(""+a);
2221 out.println("</td>");
2222 out.println("</tr>");}
2223
2224 out.println("</table>");
2225 out.println("</body>");
2226 out.println("</html>");
2227//Visible= this.setVisible(false);
2228 // new menu().setVisible(true);
2229
2230//if(i>0)
2231//out.print("You are successfully registered...");
2232}catch (Exception e2)
2233{System.out.println(e2);}
2234 out.close();
2235}
2236}
2237Q2. Create a table called employee which contains emp name, emp id,
2238designation and salary. Write a servlet code to display all the information of
2239an employee whose designation is supervisor else display only the employee
2240name and designation.
2241CODE:
2242import java.io.*;
2243import java.sql.*;
2244import javax.servlet.ServletException;
2245import javax.servlet.http.*;
2246import com.mysql.jdbc.Driver;
2247import javax.servlet.ServletContext;
2248import javax.swing.JOptionPane;
2249
2250public class register extends HttpServlet {
2251
2252@Override
2253public void doPost(HttpServletRequest request, HttpServletResponse response)
2254 throws ServletException, IOException {
2255
2256//response.setContentType("text/html");
2257PrintWriter out = response.getWriter();
2258
2259//String n=request.getParameter("phone_number");
2260//String p=request.getParameter("name");
2261//String e=request.getParameter("psw");
2262//String c=request.getParameter("gender");
2263
2264try{
2265Class.forName("com.mysql.jdbc.Driver");
2266Connection
2267con=DriverManager.getConnection("jdbc:mysql://localhost:3307/Java_DA","root","Aseem");
2268
2269System.out.println("*** Connect to the database ***");
2270String query="select * from employee where designation ='supervisor'; ";
2271String query2="select * from employee where designation !='supervisor';";
2272Statement smnt = con.createStatement();
2273//smnt.executeUpdate(query);
2274//ServletContext sc = getServletContext();
2275//sc.getRequestDispatcher("/2.html").forward(request, response);
2276 out.println("<!DOCTYPE html>");
2277 out.println("<html>");
2278 out.println("<head>");
2279 out.println("<title>You are registered</title>");
2280 out.println("</head>");
2281 out.println("<body>");
2282 out.println("<table border=1>");
2283 out.println("<tr>");
2284 out.println("<th>");
2285 out.println("EmpName");
2286 out.println("</th>");
2287 out.println("<th>");
2288 out.println("EmpId");
2289 out.println("</th>");
2290 out.println("<th>");
2291 out.println("Designation");
2292 out.println("</th>");
2293 out.println("<th>");
2294 out.println("Salary");
2295 out.println("</th>");
2296out.println("</tr>");
2297ResultSet rs = smnt.executeQuery(query);
2298while (rs.next()){
2299String name=rs.getString("empname");
2300String reg=rs.getString("empid");
2301String marks1=rs.getString("designation");
2302String marks2=rs.getString("salary");
2303 out.println("<tr>");
2304 out.println("<td>");
2305 out.println(name);
2306 out.println("</td>");
2307 out.println("<td>");
2308 out.println(reg);
2309 out.println("</td>");
2310 out.println("<td>");
2311 out.println(marks1);
2312 out.println("</td>");
2313 out.println("<td>");
2314 out.println(marks2);
2315 out.println("</td>");
2316 out.println("</tr>");}
2317 out.println("</table>");
2318 out.println("br");
2319 out.println("br");
2320 out.println("<table border=1>");
2321 out.println("<tr>");
2322 out.println("<th>");
2323 out.println("Name");
2324 out.println("</th>");
2325 out.println("<th>");
2326 out.println("designation");
2327 out.println("</th>");
2328 out.println("</tr>");
2329 ResultSet rs1 = smnt.executeQuery(query);
2330while (rs1.next()){
2331String name=rs1.getString("empname");
2332String reg=rs1.getString("empid");
2333String marks1=rs1.getString("designation");
2334String marks2=rs1.getString("salary");
2335 out.println("<tr>");
2336 out.println("<td>");
2337 out.println(name);
2338 out.println("</td>");
2339 out.println("<td>");
2340 out.println(marks1);
2341 out.println("</td>");
2342 out.println("</tr>");}
2343 out.println("</table>");
2344 out.println("</body>");
2345 out.println("</html>");
2346//Visible= this.setVisible(false);
2347 // new menu().setVisible(true);
2348
2349//if(i>0)
2350//out.print("You are successfully registered...");
2351}catch (Exception e2)
2352{System.out.println(e2);}
2353out.close();
2354}
2355}