From ab371843aca53ab802e21427d28de5a65577a694 Mon Sep 17 00:00:00 2001 From: SOZEL <80200848+TruongNhanNguyen@users.noreply.github.com> Date: Wed, 13 Mar 2024 01:49:58 +0700 Subject: [PATCH] Close `Scanner` to avoid resource leak (#5077) --- .../thealgorithms/ciphers/ProductCipher.java | 107 ++++++++--------- .../datastructures/graphs/BellmanFord.java | 109 +++++++++--------- .../datastructures/stacks/ReverseStack.java | 40 +++---- .../maths/NonRepeatingElement.java | 103 +++++++++-------- .../others/InsertDeleteInArray.java | 73 ++++++------ .../searches/RecursiveBinarySearch.java | 36 +++--- 6 files changed, 243 insertions(+), 225 deletions(-) diff --git a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java index c5ce8a9b157c..5b1d46fe9a9a 100644 --- a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java @@ -5,67 +5,68 @@ class ProductCipher { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.println("Enter the input to be encrypted: "); - String substitutionInput = sc.nextLine(); - System.out.println(" "); - System.out.println("Enter a number: "); - int n = sc.nextInt(); + try (Scanner sc = new Scanner(System.in)) { + System.out.println("Enter the input to be encrypted: "); + String substitutionInput = sc.nextLine(); + System.out.println(" "); + System.out.println("Enter a number: "); + int n = sc.nextInt(); - // Substitution encryption - StringBuffer substitutionOutput = new StringBuffer(); - for (int i = 0; i < substitutionInput.length(); i++) { - char c = substitutionInput.charAt(i); - substitutionOutput.append((char) (c + 5)); - } - System.out.println(" "); - System.out.println("Substituted text: "); - System.out.println(substitutionOutput); + // Substitution encryption + StringBuffer substitutionOutput = new StringBuffer(); + for (int i = 0; i < substitutionInput.length(); i++) { + char c = substitutionInput.charAt(i); + substitutionOutput.append((char) (c + 5)); + } + System.out.println(" "); + System.out.println("Substituted text: "); + System.out.println(substitutionOutput); - // Transposition encryption - String transpositionInput = substitutionOutput.toString(); - int modulus; - if ((modulus = transpositionInput.length() % n) != 0) { - modulus = n - modulus; + // Transposition encryption + String transpositionInput = substitutionOutput.toString(); + int modulus; + if ((modulus = transpositionInput.length() % n) != 0) { + modulus = n - modulus; - for (; modulus != 0; modulus--) { - transpositionInput += "/"; + for (; modulus != 0; modulus--) { + transpositionInput += "/"; + } } - } - StringBuffer transpositionOutput = new StringBuffer(); - System.out.println(" "); - System.out.println("Transposition Matrix: "); - for (int i = 0; i < n; i++) { - for (int j = 0; j < transpositionInput.length() / n; j++) { - char c = transpositionInput.charAt(i + (j * n)); - System.out.print(c); - transpositionOutput.append(c); + StringBuffer transpositionOutput = new StringBuffer(); + System.out.println(" "); + System.out.println("Transposition Matrix: "); + for (int i = 0; i < n; i++) { + for (int j = 0; j < transpositionInput.length() / n; j++) { + char c = transpositionInput.charAt(i + (j * n)); + System.out.print(c); + transpositionOutput.append(c); + } + System.out.println(); } - System.out.println(); - } - System.out.println(" "); - System.out.println("Final encrypted text: "); - System.out.println(transpositionOutput); + System.out.println(" "); + System.out.println("Final encrypted text: "); + System.out.println(transpositionOutput); - // Transposition decryption - n = transpositionOutput.length() / n; - StringBuffer transpositionPlaintext = new StringBuffer(); - for (int i = 0; i < n; i++) { - for (int j = 0; j < transpositionOutput.length() / n; j++) { - char c = transpositionOutput.charAt(i + (j * n)); - transpositionPlaintext.append(c); + // Transposition decryption + n = transpositionOutput.length() / n; + StringBuffer transpositionPlaintext = new StringBuffer(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < transpositionOutput.length() / n; j++) { + char c = transpositionOutput.charAt(i + (j * n)); + transpositionPlaintext.append(c); + } } - } - // Substitution decryption - StringBuffer plaintext = new StringBuffer(); - for (int i = 0; i < transpositionPlaintext.length(); i++) { - char c = transpositionPlaintext.charAt(i); - plaintext.append((char) (c - 5)); - } + // Substitution decryption + StringBuffer plaintext = new StringBuffer(); + for (int i = 0; i < transpositionPlaintext.length(); i++) { + char c = transpositionPlaintext.charAt(i); + plaintext.append((char) (c - 5)); + } - System.out.println("Plaintext: "); - System.out.println(plaintext); - sc.close(); + System.out.println("Plaintext: "); + System.out.println(plaintext); + sc.close(); + } } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index 8229c1fa947d..9f5022b44465 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -2,9 +2,13 @@ import java.util.*; -class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs -in form of edges which have start vertex, end vertex and weights. Vertices should be labelled with a -number between 0 and total number of vertices-1,both inclusive*/ +class BellmanFord /* + * Implementation of Bellman ford to detect negative cycles. Graph accepts + * inputs + * in form of edges which have start vertex, end vertex and weights. Vertices + * should be labelled with a + * number between 0 and total number of vertices-1,both inclusive + */ { int vertex, edge; @@ -36,7 +40,7 @@ public Edge(int a, int b, int c) { /** * @param p[] Parent array which shows updates in edges - * @param i Current vertex under consideration + * @param i Current vertex under consideration */ void printPath(int[] p, int i) { if (p[i] == -1) { // Found the path back to parent @@ -52,64 +56,65 @@ public static void main(String[] args) { } public void go() { // shows distance to all vertices // Interactive run for understanding the - // class first time. Assumes source vertex is 0 and - Scanner sc = new Scanner(System.in); // Grab scanner object for user input - int i, v, e, u, ve, w, j, neg = 0; - System.out.println("Enter no. of vertices and edges please"); - v = sc.nextInt(); - e = sc.nextInt(); - Edge[] arr = new Edge[e]; // Array of edges - System.out.println("Input edges"); - for (i = 0; i < e; i++) { - u = sc.nextInt(); - ve = sc.nextInt(); - w = sc.nextInt(); - arr[i] = new Edge(u, ve, w); - } - int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance - // between source - // and all vertices - int[] p = new int[v]; // Parent array for holding the paths - for (i = 0; i < v; i++) { - dist[i] = Integer.MAX_VALUE; // Initializing distance values - } - dist[0] = 0; - p[0] = -1; - for (i = 0; i < v - 1; i++) { + try ( // class first time. Assumes source vertex is 0 and + Scanner sc = new Scanner(System.in)) { + int i, v, e, u, ve, w, j, neg = 0; + System.out.println("Enter no. of vertices and edges please"); + v = sc.nextInt(); + e = sc.nextInt(); + Edge[] arr = new Edge[e]; // Array of edges + System.out.println("Input edges"); + for (i = 0; i < e; i++) { + u = sc.nextInt(); + ve = sc.nextInt(); + w = sc.nextInt(); + arr[i] = new Edge(u, ve, w); + } + int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance + // between source + // and all vertices + int[] p = new int[v]; // Parent array for holding the paths + for (i = 0; i < v; i++) { + dist[i] = Integer.MAX_VALUE; // Initializing distance values + } + dist[0] = 0; + p[0] = -1; + for (i = 0; i < v - 1; i++) { + for (j = 0; j < e; j++) { + if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { + dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update + p[arr[j].v] = arr[j].u; + } + } + } + // Final cycle for negative checking for (j = 0; j < e; j++) { if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { - dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update - p[arr[j].v] = arr[j].u; + neg = 1; + System.out.println("Negative cycle"); + break; } } - } - // Final cycle for negative checking - for (j = 0; j < e; j++) { - if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { - neg = 1; - System.out.println("Negative cycle"); - break; - } - } - if (neg == 0) { // Go ahead and show results of computation - System.out.println("Distances are: "); - for (i = 0; i < v; i++) { - System.out.println(i + " " + dist[i]); - } - System.out.println("Path followed:"); - for (i = 0; i < v; i++) { - System.out.print("0 "); - printPath(p, i); - System.out.println(); + if (neg == 0) { // Go ahead and show results of computation + System.out.println("Distances are: "); + for (i = 0; i < v; i++) { + System.out.println(i + " " + dist[i]); + } + System.out.println("Path followed:"); + for (i = 0; i < v; i++) { + System.out.print("0 "); + printPath(p, i); + System.out.println(); + } } + sc.close(); } - sc.close(); } /** * @param source Starting vertex - * @param end Ending vertex - * @param Edge Array of edges + * @param end Ending vertex + * @param Edge Array of edges */ public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index f269d08b5678..c9d2ea05778b 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -11,21 +11,22 @@ public class ReverseStack { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - System.out.println("Enter the number of elements you wish to insert in the stack"); - int n = sc.nextInt(); - int i; - Stack stack = new Stack(); - System.out.println("Enter the stack elements"); - for (i = 0; i < n; i++) { - stack.push(sc.nextInt()); - } - sc.close(); - reverseStack(stack); - System.out.println("The reversed stack is:"); - while (!stack.isEmpty()) { - System.out.print(stack.peek() + ","); - stack.pop(); + try (Scanner sc = new Scanner(System.in)) { + System.out.println("Enter the number of elements you wish to insert in the stack"); + int n = sc.nextInt(); + int i; + Stack stack = new Stack(); + System.out.println("Enter the stack elements"); + for (i = 0; i < n; i++) { + stack.push(sc.nextInt()); + } + sc.close(); + reverseStack(stack); + System.out.println("The reversed stack is:"); + while (!stack.isEmpty()) { + System.out.print(stack.peek() + ","); + stack.pop(); + } } } @@ -48,16 +49,15 @@ private static void reverseStack(Stack stack) { private static void insertAtBottom(Stack stack, int element) { if (stack.isEmpty()) { - // When stack is empty, insert the element so it will be present at the bottom of the - // stack + // When stack is empty, insert the element so it will be present at + // the bottom of the stack stack.push(element); return; } int ele = stack.peek(); - /*Keep popping elements till stack becomes empty. Push the elements once the topmost element - has moved to the bottom of the stack. - */ + // Keep popping elements till stack becomes empty. Push the elements + // once the topmost element has moved to the bottom of the stack. stack.pop(); insertAtBottom(stack, element); diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java index 86dce42f1564..01fdd5a6a5a5 100644 --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java @@ -10,61 +10,70 @@ public class NonRepeatingElement { public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - int i, res = 0; - System.out.println("Enter the number of elements in the array"); - int n = sc.nextInt(); - if ((n & 1) == 1) { - // Not allowing odd number of elements as we are expecting 2 non repeating numbers - System.out.println("Array should contain even number of elements"); - return; - } - int[] arr = new int[n]; + try (Scanner sc = new Scanner(System.in)) { + int i, res = 0; + System.out.println("Enter the number of elements in the array"); + int n = sc.nextInt(); + if ((n & 1) == 1) { + // Not allowing odd number of elements as we are expecting 2 non repeating + // numbers + System.out.println("Array should contain even number of elements"); + return; + } + int[] arr = new int[n]; - System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat"); - for (i = 0; i < n; i++) { - arr[i] = sc.nextInt(); - } + System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat"); + for (i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } - try { - sc.close(); - } catch (Exception e) { - System.out.println("Unable to close scanner" + e); - } + try { + sc.close(); + } catch (Exception e) { + System.out.println("Unable to close scanner" + e); + } - // Find XOR of the 2 non repeating elements - for (i = 0; i < n; i++) { - res ^= arr[i]; - } + // Find XOR of the 2 non repeating elements + for (i = 0; i < n; i++) { + res ^= arr[i]; + } - // Finding the rightmost set bit - res = res & (-res); - int num1 = 0, num2 = 0; + // Finding the rightmost set bit + res = res & (-res); + int num1 = 0, num2 = 0; - for (i = 0; i < n; i++) { - if ((res & arr[i]) > 0) { // Case 1 explained below - num1 ^= arr[i]; - } else { - num2 ^= arr[i]; // Case 2 explained below + for (i = 0; i < n; i++) { + if ((res & arr[i]) > 0) { // Case 1 explained below + num1 ^= arr[i]; + } else { + num2 ^= arr[i]; // Case 2 explained below + } } - } - System.out.println("The two non repeating elements are " + num1 + " and " + num2); - sc.close(); + System.out.println("The two non repeating elements are " + num1 + " and " + num2); + sc.close(); + } } /* - Explanation of the code: - let us assume we have an array [1,2,1,2,3,4] - Property of XOR: num ^ num = 0. - If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 and 2 ^ 2 would give - 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to find two's - complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's complement of 7 is 001 - and hence res = 1. There can be 2 options when we Bitise AND this res with all the elements in our - array - 1. Result will come non zero number - 2. Result will be 0. - In the first case we will XOR our element with the first number (which is initially 0) - In the second case we will XOR our element with the second number(which is initially 0) - This is how we will get non repeating elements with the help of bitwise operators. + * Explanation of the code: + * let us assume we have an array [1,2,1,2,3,4] + * Property of XOR: num ^ num = 0. + * If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 + * and 2 ^ 2 would give + * 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to + * find two's + * complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's + * complement of 7 is 001 + * and hence res = 1. There can be 2 options when we Bitise AND this res with + * all the elements in our + * array + * 1. Result will come non zero number + * 2. Result will be 0. + * In the first case we will XOR our element with the first number (which is + * initially 0) + * In the second case we will XOR our element with the second number(which is + * initially 0) + * This is how we will get non repeating elements with the help of bitwise + * operators. */ } diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java index c90cfea1fcb1..201c0ad2dd80 100644 --- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java +++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java @@ -5,46 +5,47 @@ public class InsertDeleteInArray { public static void main(String[] args) { - Scanner s = new Scanner(System.in); // Input statement - System.out.println("Enter the size of the array"); - int size = s.nextInt(); - int[] a = new int[size]; - int i; + try (Scanner s = new Scanner(System.in)) { + System.out.println("Enter the size of the array"); + int size = s.nextInt(); + int[] a = new int[size]; + int i; - // To enter the initial elements - for (i = 0; i < size; i++) { - System.out.println("Enter the element"); - a[i] = s.nextInt(); - } + // To enter the initial elements + for (i = 0; i < size; i++) { + System.out.println("Enter the element"); + a[i] = s.nextInt(); + } - // To insert a new element(we are creating a new array) - System.out.println("Enter the index at which the element should be inserted"); - int insert_pos = s.nextInt(); - System.out.println("Enter the element to be inserted"); - int ins = s.nextInt(); - int size2 = size + 1; - int[] b = new int[size2]; - for (i = 0; i < size2; i++) { - if (i <= insert_pos) { - b[i] = a[i]; - } else { - b[i] = a[i - 1]; + // To insert a new element(we are creating a new array) + System.out.println("Enter the index at which the element should be inserted"); + int insert_pos = s.nextInt(); + System.out.println("Enter the element to be inserted"); + int ins = s.nextInt(); + int size2 = size + 1; + int[] b = new int[size2]; + for (i = 0; i < size2; i++) { + if (i <= insert_pos) { + b[i] = a[i]; + } else { + b[i] = a[i - 1]; + } + } + b[insert_pos] = ins; + for (i = 0; i < size2; i++) { + System.out.println(b[i]); } - } - b[insert_pos] = ins; - for (i = 0; i < size2; i++) { - System.out.println(b[i]); - } - // To delete an element given the index - System.out.println("Enter the index at which element is to be deleted"); - int del_pos = s.nextInt(); - for (i = del_pos; i < size2 - 1; i++) { - b[i] = b[i + 1]; - } - for (i = 0; i < size2 - 1; i++) { - System.out.println(b[i]); + // To delete an element given the index + System.out.println("Enter the index at which element is to be deleted"); + int del_pos = s.nextInt(); + for (i = del_pos; i < size2 - 1; i++) { + b[i] = b[i + 1]; + } + for (i = 0; i < size2 - 1; i++) { + System.out.println(b[i]); + } + s.close(); } - s.close(); } } diff --git a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java index 0a84aa1d64ce..8860f3380e31 100644 --- a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java @@ -3,6 +3,7 @@ // File Name should be RecursiveBinarySearch.java // Explanation:- https://www.tutorialspoint.com/java-program-for-binary-search-recursive package com.thealgorithms.searches; + import java.util.*; // Create a SearchAlgorithm class with a generic type @@ -47,28 +48,29 @@ public int binsear(T[] arr, int left, int right, T target) { } public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - // User inputs - System.out.print("Enter the number of elements in the array: "); - int n = sc.nextInt(); + try (Scanner sc = new Scanner(System.in)) { + // User inputs + System.out.print("Enter the number of elements in the array: "); + int n = sc.nextInt(); - Integer[] a = new Integer[n]; // You can change the array type as needed + Integer[] a = new Integer[n]; // You can change the array type as needed - System.out.println("Enter the elements in sorted order:"); + System.out.println("Enter the elements in sorted order:"); - for (int i = 0; i < n; i++) { - a[i] = sc.nextInt(); - } + for (int i = 0; i < n; i++) { + a[i] = sc.nextInt(); + } - System.out.print("Enter the target element to search for: "); - int t = sc.nextInt(); + System.out.print("Enter the target element to search for: "); + int t = sc.nextInt(); - RecursiveBinarySearch searcher = new RecursiveBinarySearch<>(); - int res = searcher.find(a, t); + RecursiveBinarySearch searcher = new RecursiveBinarySearch<>(); + int res = searcher.find(a, t); - if (res == -1) - System.out.println("Element not found in the array."); - else - System.out.println("Element found at index " + res); + if (res == -1) + System.out.println("Element not found in the array."); + else + System.out.println("Element found at index " + res); + } } }