Anzeige

# Computer java programs

STUDENT um R R INTER COLLEGE HARDOI
7. Feb 2018
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
String Handling
1 von 50
Anzeige

### Computer java programs

1. PROGRAM 51 Write a program in Java to display the pattern like right angle triangle with a number. SOLUTION: importjava.util.Scanner; public class Pattern3{ public static void main(String[] args) { inti,j,n; System.out.print("Input number of rows : "); Scanner in = new Scanner(System.in); n =in.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) System.out.print(j); System.out.println(""); }}} OUTPUT: Input number of rows : 10 1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
2. PROGRAM 52 Write a program in Java to make such a pattern like a pyramid with a number which will repeat the number in the same row. SOLUTION: importjava.util.Scanner; public class Pattern4{ public static void main(String[] args) { inti,j,n,s,x; System.out.print ("Input number of rows : "); Scanner in = new Scanner(System.in); n =in.nextInt(); s=n+4-1; for(i=1;i<=n;i++) { for(x=s;x!=0;x--) { System.out.print(" "); } for(j=1;j<=i;j++){ System.out.print(i+" "); } System.out.println(); s--; }}} OUTPUT: Input Number of Rows : 4 1 2 2 3 3 3 4 4 4 4
3. PROGRAM 53 Write a Java program to display Pascal's triangle. SOLUTION: importjava.util.Scanner; public class Pattern5 { public static void main(String[] args) { intno_row,c=1,blk,i,j; System.out.print("Input number of rows: "); Scanner in = new Scanner(System.in); no_row=in.nextInt(); for(i=0;i<no_row;i++) { for(blk=1;blk<=no_row-i;blk++) System.out.print(" "); for(j=0;j<=i;j++) { if (j==0||i==0) c=1; else c=c*(i-j+1)/j; System.out.print(" "+c); } System.out.print("n"); }}} OUTPUT: Input number of rows: 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
4. PROGRAM 54 Write a Java program that reads an integer and check whether it is negative, zero, or positive. SOLUTION: importjava.util.Scanner; public class POSITIVE{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input a number: "); int n =in.nextInt(); if (n > 0) { System.out.println("Number is positive"); } else if (n < 0) { System.out.println("Number is negative"); } else { System.out.println("Number is zero"); } } } OUTPUT: Input a number: 7 Number is positive
5. PROGRAM 55 Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise. SOLUTION: importjava.util.Scanner; public class Number { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input first number: "); double x =in.nextDouble(); System.out.print("Input second number: "); double y =in.nextDouble(); System.out.print("Input third number: "); double z =in.nextDouble(); if (x < y && y < z){ System.out.println("Increasing order"); } else if (x > y && y > z) { System.out.println("Decreasing order"); } else{ System.out.println("Neither increasing or decreasing order"); }}} OUTPUT: Input first number: 1524 Input second number: 2345 Input third number: 3321 Increasing order
6. PROGRAM 56 Write a Java program to sort a numeric array and a string array. SOLUTION: importjava.util.Arrays; public class Array1 { public static void main(String[] args){ int[] my_array1 = {1789, 2035, 1899, 1456, 2013,1458, 2458,1254,1472, 2365,1456, 2165, 1457, 2456}; String[]my_array2={"Java","Python","PHP","C#","CProgramming", "C++"} System.out.println("Original numeric array :"+Arrays.toString(my_array1)); Arrays.sort(my_array1); System.out.println("Sorted numeric array : "+Arrays.toString(my_array1)); System.out.println("Original string array : "+Arrays.toString(my_array2)); Arrays.sort(my_array2); System.out.println("Sorted string array : "+Arrays.toString(my_array2)); } } OUTPUT: Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165, 1457, 2456] Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365, 2456, 2458] Original string array : [Java, Python, PHP, C#, C Programming, C++] Sorted string array :[C Programming, C#, C++, Java, PHP, Python]
7. PROGRAM 57 Write a Java program to calculate the average value of array elements. SOLUTION: publicclassArray2 { publicstaticvoidmain(String[]args) { int[] numbers =newint[]{20,30,25,35,-16,60,-100}; //calculate sum of all array elements int sum =0; for(inti=0;i<numbers.length;i++) { sum= sum + numbers[i]; //calculate average value double average = sum /numbers.length; System.out.println("Average value of the array elements is : "+ average); } } } OUTPUT: Average value of the array elements is : 7.0
8. PROGRAM 58 Write a Java program to insert an element (specific position) into an array. SOLUTION: importjava.util.Arrays; public class Array3 { public static void main(String[] args) { int[] my_array= {25, 14, 56, 15, 36, 56, 77, 18, 29, 49}; // Insert an element in 3rd position of the array (index->2, value->5) intIndex_position= 2; intnewValue= 5; System.out.println("Original Array : "+Arrays.toString(my_array)); for(inti=my_array.length-1; i>Index_position; i--){ my_array[i] =my_array[i-1]; } my_array[Index_position] =newValue; System.out.println("New Array: "+Arrays.toString(my_array)); } } OUTPUT: Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49] New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29]
9. PROGRAM 59 Write a Java program to replace every element with the next greatest element (from right side) in an given array of integers. Solution: import java.io.*; importjava.util.Arrays; classArray4 { public static void main (String[] args) { intnums[] = {45, 20, 100, 23, -5, 2, -6}; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(nums)); result = next_greatest_num(nums); System.out.println("The modified array:"); System.out.println(Arrays.toString(result)); } staticint [] next_greatest_num(intarr_nums[]) { int size = arr_nums.length; intmax_from_right_num = arr_nums[size-1]; arr_nums[size-1] = -1; for (inti = size-2; i>= 0; i--) { int temp = arr_nums[i]; arr_nums[i] = max_from_right_num; if(max_from_right_num< temp) max_from_right_num = temp; } returnarr_nums; } } OUTPUT: Original Array [45, 20, 100, 23, -5, 2, -6] The modified array:[100, 100, 23, 2, 2, -6, -1]
10. PROGRAM 60 Write a Java program to separate even and odd numbers of an given array of integers. Put all even numbers first, and then odd numbers. Solution: importjava.util.Arrays; class Array5{ public static void main (String[] args){ intnums[] = {20, 12, 23, 17, 7, 8, 10, 2, 1, 0}; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(nums)); result=separate_odd_even(nums); System.out.print("Array after separation "); System.out.println(Arrays.toString(result));} staticint [] separate_odd_even(intarr[]){ intleft_side= 0, right_side=arr.length- 1; while (left_side<right_side){ while (arr[left_side]%2 == 0 &&left_side<right_side) left_side++; while (arr[right_side]%2 == 1 &&left_side<right_side) right_side--; if (left_side<right_side){ int temp =arr[left_side]; arr[left_side] =arr[right_side]; arr[right_side] = temp; left_side++; right_side--;}} returnarr;}} OUTPUT: Original Array [45, 20, 100, 23, -5, 2, -6] The modified array:[100, 100, 23, 2, 2, -6, -1]
11. PROGRAM 61 Write a Java program to separate 0s on left side and 1s on right side of an array of 0s and 1s in random order. Solution: importjava.util.Arrays; classArray6 { public static void main(String[] args) { intarr[] = new int[]={ 0, 0, 1, 1, 0, 1, 1, 1,0 }; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(arr)); int n = arr.length; result = separate_0_1(arr, n); System.out.println("New Array "); System.out.println(Arrays.toString(result)); } staticint [] separate_0_1(intarr[], int n) { int count = 0; for (inti = 0; i< n; i++) if (arr[i] == 0) count++;} for (inti = 0; i< count; i++) arr[i] = 0; for (inti = count; i< n; i++) arr[i] = 1; returnarr; }} OUTPUT: Original Array [0, 0, 1, 1, 0, 1, 1, 1, 0] New Array [0, 0, 0, 0, 1, 1, 1, 1, 1]
12. PROGRAM 62 Write a Java program to find the rotation count in a given rotated sorted array of integers. Solution: importjava.util.*; importjava.lang.*; import java.io.*; public class Array7 { staticintcount_rotations(intarr_int[], int n) { intmin_val=arr_int[0], min_index=-1; for (inti= 0; i< n; i++) { if (min_val>arr_int[i]) { min_val=arr_int[i]; min_index=i; } } returnmin_index; } public static void main (String[] args) { intarr_int[] = {35, 32, 30, 14, 18, 21, 27}; // intarr_int[] = {35, 32, 14, 18, 21, 27}; // intarr_int[] = {35, 14, 18, 21, 27}; int n =arr_int.length; System.out.println(count_rotations(arr_int, n)); }} OUTPUT: Number of Rotations = 3
13. PROGRAM 63 Write a Java program to find all pairs of elements in an array whose sum is equal to a specified number Solution: public class Array8 { static void pairs_value(intinputArray[], intinputNumber) { System.out.println("Pairs of elements and their sum : "); for (inti= 0; i<inputArray.length; i++) { for (int j = i+1; j <inputArray.length; j++) { if(inputArray[i]+inputArray[j] ==inputNumber) { System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber); } }}} public static void main(String[] args) { pairs_value(new int[] {2, 7, 4, -5, 11, 5, 20}, 15); pairs_value(new int[] {14, -15, 9, 16, 25, 45, 12, 8}, 30); } } OUTPUT: Enter the Number = 15 Pairs of elements and their sum :4 + 11 = 15 -5 + 20 = 15
14. PROGRAM 64 Write a Java program to add two matrices of the same size Solution: importjava.util.Scanner; public class Array9 { public static void main(String args[]) { int m, n, c, d; Scanner in = new Scanner(System.in); System.out.println("Input number of rows of matrix"); m =in.nextInt(); System.out.println("Input number of columns of matrix"); n =in.nextInt(); int array1[][] = new int[m][n]; int array2[][] = new int[m][n]; int sum[][] = new int[m][n]; System.out.println("Input elements of first matrix"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { array1[c][d] =in.nextInt(); System.out.println("Input the elements of second matrix"); }} for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) array2[c][d] =in.nextInt(); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = array1[c][d] + array2[c][d]; System.out.println("Sum of the matrices:-");
15. for ( c = 0 ; c < m ; c++ ){ for ( d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"t"); System.out.println(); } }} OUTPUT: Input number of rows of matrix 2 Input number of columns of matrix 2 Input elements of first matrix 1 2 34 Input the elements of second matrix 5 6 7 8 Sum of the matrices:- 6 8 10 12
16. PROGRAM 65 Write a Java program to check if an array of integers without 0 and -1. Solution: importjava.util.*; import java.io.*; public class Array10 { public static void main(String[] args) { int[] array_nums= {50, 77, 12, 54, -11}; System.out.println("Original Array: "+Arrays.toString(array_nums)); System.out.println("Result: "+test(array_nums)); } public static boolean test(int[] numbers) { for (int number : numbers) { if (number == 0 || number ==-1) { return false; } } return true; } } OUTPUT: Original Array: [50, 77, 12, 54, -11] Result: true
17. PROGRAM 66 Write a Java program to check if the sum of all the 10's in the array is exactly 30. Return false if the condition does not satisfy, otherwise true. Solution: importjava.util.*; import java.io.*; public class Array11 { public static void main(String[] args) { int[] array_nums= {10, 77, 10, 54, -11, 10}; System.out.println("Original Array: "+Arrays.toString(array_nums)); intsearch_num= 10; intfixed_sum= 30; System.out.println("Result: "+result(array_nums, search_num, fixed_sum)); } public static boolean result(int[] numbers, intsearch_num, intfixed_sum) { inttemp_sum= 0; for (int number : numbers) { if (number ==search_num) { temp_sum+=search_num; } if (temp_sum>fixed_sum) { break; } } returntemp_sum==fixed_sum; }} OUTPUT: Original Array: [10, 77, 10, 54, -11, 10] Result: true
18. PROGRAM 67 Write a Java program to check if an array of integers contains two specified elements 65 and 77. Solution: importjava.util.*; import java.io.*; public class Array12 { public static void main(String[] args) { int[] array_nums= {77, 77, 65, 65, 65, 77}; System.out.println("Original Array: "+Arrays.toString(array_nums)); int num1 = 77; int num2 = 65; System.out.println("Result: "+result(array_nums, num1, num2)); } public static boolean result(int[] array_nums, int num1, int num2) { for (int number :array_nums) { boolean r = number != num1 && number != num2; if (r) { return false; } } return true; } } OUTPUT: Original Array: [77, 77, 65, 65, 65, 77] Result: true
19. PROGRAM 68 Write a Java program to get the character at the given index within the String. SOLUTION: public class String1 { public static void main(String[] args) { String str= "Java Exercises!"; System.out.println("Original String = " +str); // Get the character at positions 0 and 10. int index1 =str.charAt(0); int index2 =str.charAt(10); // Print out the results. System.out.println("The character at position 0 is " + (char)index1); System.out.println("The character at position 10 is " + (char)index2); } } OUTPUT: Original String = Java Exercises! The character at position 0 is J The character at position 10 is i
20. PROGRAM 69 Write a Java program to trim any leading or trailing whitespace from a given string. Solution: publicclassString2{ publicstaticvoidmain(String[]args) { String str=" Java Exercises "; // Trim the whitespace from the front and back of the // String. String new_str=str.trim(); // Display the strings for comparison. System.out.println("Original String: "+str); System.out.println("New String: "+new_str); } } OUTPUT: Original String: Java Exercises New String: Java Exercises
21. PROGRAM 70 Write a program in java To find minimum value using overloading. Solution: public class ExampleOverloading{ public static void main(String[] args){ int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = minFunction(a, b); double result2 = minFunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2);} public static intminFunction(int n1, int n2) { intmin;if (n1 > n2)min = n2; elsem in = n1; return min; } public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; elsemin = n1; return min; } } OUTPUT: Minimum Value = 6 Minimum Value = 7.3
22. PROGRAM 71 Write a program in Java to show the use of this keyword. Solution: public class This_Example { intnum = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(intnum) { this(); this.num = num; } public void greet() { System.out.println("Hi Welcome to Tutorialspoint"); } public void print() { intnum = 20; System.out.println("value of local variable num is : "+num); System.out.println("value of instance variable num is : "+this.num); this.greet(); } public static void main(String[] args) { This_Example obj1 = new This_Example(); obj1.print(); This_Exampleobj2 = new This_Example(30); obj2.print(); }} OUTPUT: This is an example program on keyword this value of local variable numis : 20 value of instance variable num is : 10
23. PROGRAM 72 Write a program in java to demonstrate InputStream and OutputStream. SOLUTION: import java.io.*; public class fileStreamTest { public static void main(String args[]) { try { bytebWrite [] = {11,21,3,40,5}; OutputStreamos = new FileOutputStream("test.txt"); for(int x = 0; x <bWrite.length ; x++) { os.write(bWrite[x] ); } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(inti = 0; i< size; i++) { System.out.print((char)is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); }}} OUTPUT: The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
24. PROGRAM 73 Write a program in java to create "/tmp/user/java/bin" directory. SOLUTION: importjava.io.File; public class CreateDir { public static void main(String args[]) { String dirname ="/tmp/user/java/bin"; File d = new File(dirname); // Create directory now. d.mkdirs(); } } OUTPUT: Compile and execute the above code to create "/tmp/user/java/bin".
25. PROGRAM 74 Write a program in java to list down all the files and directories available in a directory. SOLUTION: importjava.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); }} catch (Exception e) { // if any error occurs e.printStackTrace(); } }} OUTPUT: test1.txt test2.txt ReadDir.java ReadDir.class
26. PROGRAM 75 Write a program in java to throw Exceptions occurred by Index of an array public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } OUTPUT: Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
27. PROGRAM 76 Write a program in Java to print the multiplication of two matrices. public class MatrixMultiplicationExample { public static void main(String args[]) { int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; } System.out.print(c[i][j]+" "); } System.out.println();//new line }}} OUTPUT: First matrix: Second matrix: 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 Multiplied Matrix: 6 6 6 12 12 12 18 18 18
28. PROGRAM 77 Write a Java program to find the longest word in a text file SOLUTION: importjava.util.Scanner; import java.io.*; public class Exercise18 { public static void main(String [ ] args) throws FileNotFoundException { new Exercise18().findLongestWords(); } public String findLongestWords() throws FileNotFoundException { String longest_word= ""; String current; Scanner sc= new Scanner(new File("/home/students/test.txt")); while (sc.hasNext()) { current=sc.next(); if (current.length() >longest_word.length()) { longest_word= current; } } System.out.println("n"+longest_word+"n"); returnlongest_word; } } OUTPUT: general-purpose,
29. PROGRAM 78 Write a Java program to write and read a plain text file. SOLUTION: import java.io.*; public class Eexercise15 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; try { String filename= "/home/students/myfile.txt"; FileWriterfw= new FileWriter(filename,false); fw.write("Python Exercisesn"); fw.close(); BufferedReaderbr= new BufferedReader(new FileReader("/home/students/myfile.txt")); while (strLine!= null) { sb.append(strLine); sb.append(System.lineSeparator()); strLine=br.readLine(); System.out.println(strLine); } br.close(); } catch(IOExceptionioe) { System.err.println("IOException: " +ioe.getMessage()); }}} OUTPUT: Python Exercises Null
30. PROGRAM 79 Write a Java program to append text to an existing file. SOLUTION: importjava.io.FileWriter; public class Exercise16 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; try{ String filename= "/home/students/myfile.txt"; FileWriterfw= new FileWriter(filename,true); fw.write("Java Exercisesn"); fw.close(); BufferedReaderbr= new BufferedReader(new FileReader("/home/students/myfile.txt")); //read the file content while (strLine!= null) { sb.append(strLine); sb.append(System.lineSeparator()); strLine=br.readLine(); System.out.println(strLine); } br.close(); } catch(IOExceptionioe){ System.err.println("IOException: " +ioe.getMessage()); }}} OUTPUT: Python Exercises Java Exercises null
32. PROGRAM 81 Write a program to show the Dynamic Method Dispatch using inheritance. SOLUTION: class parent1{ void sum(inti, int j){ System.out.println(“Parent class” + (i+j)); }} class child1 extends parent1{ void sum(inti, int j){ System.out.println(“Child class” + (i+j));}} classdynamic_test{ public static void main(String args[]){ parent1 p1=new parent1(); child1 c1=new child1(); parent1Refi; Refi=p1; Refi.sum(10,20); Refi=c1; Refi.sum(20,30); }} Output: Parent class 30 Child class 50
33. PROGRAM: 82 Write a program to accept 10 different word in array and pass the array to function. Search the word enter by the user is present or not. SOLUTION: import java.io.*; class Searching{ int search(String name[],String ns){ inti,p=0; for(j=0;j<10;j++){ if(name[j].equals(ns)) p=1;} return p;} public static void main()throws IOException{ inti,k=0; String name[]=new String[10];String ns; BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); Searching ob=new Searching(); System.out.println(“Enter 10 names”); for(i=0;i<10;i++){ name[i]=br.readLine();} System.out.println(“Enter the name to be searched:”); ns=in.readLine(); k=ob.search(name,ns); if(k==1) System.out.println(“Search successful”); else System.out.println(“NO such name is present”); }} OUTPUT: Enters 10 names aman, jyoti, deepa, pawan, mayank, arif, abhishek, vishal, lavi, ravi Enter the name to be searched: arjun No such name is present
34. PROGRAM: 83 Write a program in java to accept two numbers and find their sum using function by creating the object of class. SOLUTION: import java.io.*; public class Addition{ int sum(inta,int b){ int c; c=a+b; return c; } public static void main()throws IOException{ intm,n,k; BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); Addition ob=new Addition(); System.out.println(“Enter two numbers”); m=Integer.parseInt(br.readLine()); n=Integer.parseInt(br.readLine()); k=ob.sum(m,n); System.out.println(“The sum of two numbers:” + k); } } OUTPUT: Enter two numbers 3 4 The sum of two numbers: 7
35. PROGRAM: 84 Write a program to find all combination of four elements of an given array whose sum is equal to a given value. SOLUTION: importjava.util.*; importjava.lang.*; class Main { public static void main(String args[]) { intnum[]={10, 20, 30, 40, 1, 2}; int n=num.length; int s=53; System.out.println(“The given:” + s); System.out.println(“The combination of four elements:”); for(inti=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ for(int k=j+1;k<n-1;k++){ for(int l=k+1;l<n;l++) { if(num[i]+num[j]+num[k]+num[l]==s) System.out.print(num[i]+ “ “ + num[j]+ “ “ + num[k]+ “ “+ num[l]); }}}} }} OUTPUT: Given value: 53 Combination of four elements: 10 40 1 2 20 30 1 2
36. PROGRAM 85 Write a Java program to store text file content line by line into an array. SOLUTION: importjava.util.Arrays; public class Exercise14 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; List<String> list = new ArrayList<String>(); try { BufferedReaderbr= new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine!= null) { strLine=br.readLine(); sb.append(strLine); sb.append(System.lineSeparator()); strLine=br.readLine(); if (strLine==null) break; list.add(strLine);} System.out.println(Arrays.toString(list.toArray())); br.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Unable to read the file."); }}} OUTPUT: [Append this text.Append this text.Append this text., Append this text., Append this text.]
37. PROGRAM 86 Write a java program to read a file line by line and store it into a variable. SOLUTION: importjava.io.FileReader; public class exercise13 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; String str_data= ""; try { BufferedReaderbr= new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine!= null) { if (strLine== null) break; str_data+=strLine; strLine=br.readLine(); } System.out.println(str_data); br.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Unable to read the file."); }}} OUTPUT: Welcome to w3resource.com.Append this text.Appendthistext.Append this text.Append this text.Append this text.Append this text.Append this text.
38. PROGRAM 87 Write a Java program to print all the LEADERS in the array. Note: An element is leader if it is greater than all the elements to its right side. SOLUTION: importjava.util.Arrays; class Main { public static void main(String[] args) { intarr[] = {10, 9, 14, 23, 15, 0, 9}; int size = arr.length; for (inti = 0; i< size; i++) { int j; for (j = i + 1; j < size; j++) { if (arr[i] <= arr[j]) break; } if (j == size) System.out.print(arr[i] + " "); } } } OUTPUT: 23 15 9
39. PROGRAM 88 Write a Java program to find the sum of the two elements of a given array which is equal to a given integer. SOLUTION: importjava.util.*; public class Exercise35{ public static ArrayList<Integer>two_sum_array_target(final List<Integer> a, int b) { HashMap<Integer, Integer>my_map= new HashMap<Integer, Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); result.add(0); result.add(0); for(inti= 0; i<a.size(); i++){ if(my_map.containsKey(a.get(i))){ int index =my_map.get(a.get(i)); result.set(0, index + 1); result.set(1, i+ 1); break;} else{ my_map.put(b -a.get(i), i); }} return result; } public static void main(String[] args){ ArrayList<Integer>my_array= new ArrayList<Integer>(); my_array.add(1); my_array.add(2);my_array.add(4);my_array.add(5);my_array.add(6); int target = 6; ArrayList<Integer> result =two_sum_array_target(my_array, target); for(inti: result) System.out.print("Index: "+i+ " ");}} OUTPUT: Index 1 Index ⁴