Close Scanner to avoid resource leak (#5077)

This commit is contained in:
SOZEL 2024-03-13 01:49:58 +07:00 committed by GitHub
parent 47a9b1b647
commit ab371843ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 255 additions and 237 deletions

View File

@ -5,67 +5,68 @@ import java.util.Scanner;
class ProductCipher { class ProductCipher {
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter the input to be encrypted: "); System.out.println("Enter the input to be encrypted: ");
String substitutionInput = sc.nextLine(); String substitutionInput = sc.nextLine();
System.out.println(" "); System.out.println(" ");
System.out.println("Enter a number: "); System.out.println("Enter a number: ");
int n = sc.nextInt(); int n = sc.nextInt();
// Substitution encryption // Substitution encryption
StringBuffer substitutionOutput = new StringBuffer(); StringBuffer substitutionOutput = new StringBuffer();
for (int i = 0; i < substitutionInput.length(); i++) { for (int i = 0; i < substitutionInput.length(); i++) {
char c = substitutionInput.charAt(i); char c = substitutionInput.charAt(i);
substitutionOutput.append((char) (c + 5)); 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;
for (; modulus != 0; modulus--) {
transpositionInput += "/";
} }
} System.out.println(" ");
StringBuffer transpositionOutput = new StringBuffer(); System.out.println("Substituted text: ");
System.out.println(" "); System.out.println(substitutionOutput);
System.out.println("Transposition Matrix: ");
for (int i = 0; i < n; i++) { // Transposition encryption
for (int j = 0; j < transpositionInput.length() / n; j++) { String transpositionInput = substitutionOutput.toString();
char c = transpositionInput.charAt(i + (j * n)); int modulus;
System.out.print(c); if ((modulus = transpositionInput.length() % n) != 0) {
transpositionOutput.append(c); modulus = n - modulus;
for (; modulus != 0; modulus--) {
transpositionInput += "/";
}
} }
System.out.println(); StringBuffer transpositionOutput = new StringBuffer();
} System.out.println(" ");
System.out.println(" "); System.out.println("Transposition Matrix: ");
System.out.println("Final encrypted text: "); for (int i = 0; i < n; i++) {
System.out.println(transpositionOutput); for (int j = 0; j < transpositionInput.length() / n; j++) {
char c = transpositionInput.charAt(i + (j * n));
// Transposition decryption System.out.print(c);
n = transpositionOutput.length() / n; transpositionOutput.append(c);
StringBuffer transpositionPlaintext = new StringBuffer(); }
for (int i = 0; i < n; i++) { System.out.println();
for (int j = 0; j < transpositionOutput.length() / n; j++) {
char c = transpositionOutput.charAt(i + (j * n));
transpositionPlaintext.append(c);
} }
} System.out.println(" ");
System.out.println("Final encrypted text: ");
System.out.println(transpositionOutput);
// Substitution decryption // Transposition decryption
StringBuffer plaintext = new StringBuffer(); n = transpositionOutput.length() / n;
for (int i = 0; i < transpositionPlaintext.length(); i++) { StringBuffer transpositionPlaintext = new StringBuffer();
char c = transpositionPlaintext.charAt(i); for (int i = 0; i < n; i++) {
plaintext.append((char) (c - 5)); for (int j = 0; j < transpositionOutput.length() / n; j++) {
} char c = transpositionOutput.charAt(i + (j * n));
transpositionPlaintext.append(c);
}
}
System.out.println("Plaintext: "); // Substitution decryption
System.out.println(plaintext); StringBuffer plaintext = new StringBuffer();
sc.close(); 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();
}
} }
} }

View File

@ -2,9 +2,13 @@ package com.thealgorithms.datastructures.graphs;
import java.util.*; import java.util.*;
class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs class BellmanFord /*
in form of edges which have start vertex, end vertex and weights. Vertices should be labelled with a * Implementation of Bellman ford to detect negative cycles. Graph accepts
number between 0 and total number of vertices-1,both inclusive*/ * 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; int vertex, edge;
@ -36,7 +40,7 @@ number between 0 and total number of vertices-1,both inclusive*/
/** /**
* @param p[] Parent array which shows updates in edges * @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) { void printPath(int[] p, int i) {
if (p[i] == -1) { // Found the path back to parent if (p[i] == -1) { // Found the path back to parent
@ -52,64 +56,65 @@ number between 0 and total number of vertices-1,both inclusive*/
} }
public void go() { // shows distance to all vertices // Interactive run for understanding the public void go() { // shows distance to all vertices // Interactive run for understanding the
// class first time. Assumes source vertex is 0 and try ( // class first time. Assumes source vertex is 0 and
Scanner sc = new Scanner(System.in); // Grab scanner object for user input Scanner sc = new Scanner(System.in)) {
int i, v, e, u, ve, w, j, neg = 0; int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please"); System.out.println("Enter no. of vertices and edges please");
v = sc.nextInt(); v = sc.nextInt();
e = sc.nextInt(); e = sc.nextInt();
Edge[] arr = new Edge[e]; // Array of edges Edge[] arr = new Edge[e]; // Array of edges
System.out.println("Input edges"); System.out.println("Input edges");
for (i = 0; i < e; i++) { for (i = 0; i < e; i++) {
u = sc.nextInt(); u = sc.nextInt();
ve = sc.nextInt(); ve = sc.nextInt();
w = sc.nextInt(); w = sc.nextInt();
arr[i] = new Edge(u, ve, w); arr[i] = new Edge(u, ve, w);
} }
int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance
// between source // between source
// and all vertices // and all vertices
int[] p = new int[v]; // Parent array for holding the paths int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
dist[i] = Integer.MAX_VALUE; // Initializing distance values dist[i] = Integer.MAX_VALUE; // Initializing distance values
} }
dist[0] = 0; dist[0] = 0;
p[0] = -1; p[0] = -1;
for (i = 0; i < v - 1; i++) { for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) { 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) { 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 dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u; p[arr[j].v] = arr[j].u;
}
} }
} }
} // Final cycle for negative checking
// Final cycle for negative checking for (j = 0; j < e; j++) {
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) {
if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { neg = 1;
neg = 1; System.out.println("Negative cycle");
System.out.println("Negative cycle"); break;
break; }
} }
} if (neg == 0) { // Go ahead and show results of computation
if (neg == 0) { // Go ahead and show results of computation System.out.println("Distances are: ");
System.out.println("Distances are: "); for (i = 0; i < v; i++) {
for (i = 0; i < v; i++) { System.out.println(i + " " + dist[i]);
System.out.println(i + " " + dist[i]); }
} System.out.println("Path followed:");
System.out.println("Path followed:"); for (i = 0; i < v; i++) {
for (i = 0; i < v; i++) { System.out.print("0 ");
System.out.print("0 "); printPath(p, i);
printPath(p, i); System.out.println();
System.out.println(); }
} }
sc.close();
} }
sc.close();
} }
/** /**
* @param source Starting vertex * @param source Starting vertex
* @param end Ending vertex * @param end Ending vertex
* @param Edge Array of edges * @param Edge Array of edges
*/ */
public void show(int source, int end, public void show(int source, int end,
Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray()

View File

@ -11,21 +11,22 @@ import java.util.Stack;
public class ReverseStack { public class ReverseStack {
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter the number of elements you wish to insert in the stack"); System.out.println("Enter the number of elements you wish to insert in the stack");
int n = sc.nextInt(); int n = sc.nextInt();
int i; int i;
Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> stack = new Stack<Integer>();
System.out.println("Enter the stack elements"); System.out.println("Enter the stack elements");
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
stack.push(sc.nextInt()); stack.push(sc.nextInt());
} }
sc.close(); sc.close();
reverseStack(stack); reverseStack(stack);
System.out.println("The reversed stack is:"); System.out.println("The reversed stack is:");
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
System.out.print(stack.peek() + ","); System.out.print(stack.peek() + ",");
stack.pop(); stack.pop();
}
} }
} }
@ -48,16 +49,15 @@ public class ReverseStack {
private static void insertAtBottom(Stack<Integer> stack, int element) { private static void insertAtBottom(Stack<Integer> stack, int element) {
if (stack.isEmpty()) { if (stack.isEmpty()) {
// When stack is empty, insert the element so it will be present at the bottom of the // When stack is empty, insert the element so it will be present at
// stack // the bottom of the stack
stack.push(element); stack.push(element);
return; return;
} }
int ele = stack.peek(); int ele = stack.peek();
/*Keep popping elements till stack becomes empty. Push the elements once the topmost element // Keep popping elements till stack becomes empty. Push the elements
has moved to the bottom of the stack. // once the topmost element has moved to the bottom of the stack.
*/
stack.pop(); stack.pop();
insertAtBottom(stack, element); insertAtBottom(stack, element);

View File

@ -10,61 +10,70 @@ import java.util.Scanner;
public class NonRepeatingElement { public class NonRepeatingElement {
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); try (Scanner sc = new Scanner(System.in)) {
int i, res = 0; int i, res = 0;
System.out.println("Enter the number of elements in the array"); System.out.println("Enter the number of elements in the array");
int n = sc.nextInt(); int n = sc.nextInt();
if ((n & 1) == 1) { if ((n & 1) == 1) {
// Not allowing odd number of elements as we are expecting 2 non repeating numbers // Not allowing odd number of elements as we are expecting 2 non repeating
System.out.println("Array should contain even number of elements"); // numbers
return; 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();
}
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];
}
// 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
} }
} int[] arr = new int[n];
System.out.println("The two non repeating elements are " + num1 + " and " + num2); System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
sc.close(); for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
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];
}
// 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
}
}
System.out.println("The two non repeating elements are " + num1 + " and " + num2);
sc.close();
}
} }
/* /*
Explanation of the code: * Explanation of the code:
let us assume we have an array [1,2,1,2,3,4] * let us assume we have an array [1,2,1,2,3,4]
Property of XOR: num ^ num = 0. * 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 * If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1
0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to find two's * and 2 ^ 2 would give
complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's complement of 7 is 001 * 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to
and hence res = 1. There can be 2 options when we Bitise AND this res with all the elements in our * find two's
array * complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's
1. Result will come non zero number * complement of 7 is 001
2. Result will be 0. * and hence res = 1. There can be 2 options when we Bitise AND this res with
In the first case we will XOR our element with the first number (which is initially 0) * all the elements in our
In the second case we will XOR our element with the second number(which is initially 0) * array
This is how we will get non repeating elements with the help of bitwise operators. * 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.
*/ */
} }

View File

@ -5,46 +5,47 @@ import java.util.*;
public class InsertDeleteInArray { public class InsertDeleteInArray {
public static void main(String[] args) { public static void main(String[] args) {
Scanner s = new Scanner(System.in); // Input statement try (Scanner s = new Scanner(System.in)) {
System.out.println("Enter the size of the array"); System.out.println("Enter the size of the array");
int size = s.nextInt(); int size = s.nextInt();
int[] a = new int[size]; int[] a = new int[size];
int i; int i;
// To enter the initial elements // To enter the initial elements
for (i = 0; i < size; i++) { for (i = 0; i < size; i++) {
System.out.println("Enter the element"); System.out.println("Enter the element");
a[i] = s.nextInt(); 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];
} }
}
b[insert_pos] = ins;
for (i = 0; i < size2; i++) {
System.out.println(b[i]);
}
// To delete an element given the index // To insert a new element(we are creating a new array)
System.out.println("Enter the index at which element is to be deleted"); System.out.println("Enter the index at which the element should be inserted");
int del_pos = s.nextInt(); int insert_pos = s.nextInt();
for (i = del_pos; i < size2 - 1; i++) { System.out.println("Enter the element to be inserted");
b[i] = b[i + 1]; 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]);
}
// 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();
} }
for (i = 0; i < size2 - 1; i++) {
System.out.println(b[i]);
}
s.close();
} }
} }

View File

@ -3,6 +3,7 @@
// File Name should be RecursiveBinarySearch.java // File Name should be RecursiveBinarySearch.java
// Explanation:- https://www.tutorialspoint.com/java-program-for-binary-search-recursive // Explanation:- https://www.tutorialspoint.com/java-program-for-binary-search-recursive
package com.thealgorithms.searches; package com.thealgorithms.searches;
import java.util.*; import java.util.*;
// Create a SearchAlgorithm class with a generic type // Create a SearchAlgorithm class with a generic type
@ -47,28 +48,29 @@ public class RecursiveBinarySearch<T extends Comparable<T>> extends SearchAlgori
} }
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); try (Scanner sc = new Scanner(System.in)) {
// User inputs // User inputs
System.out.print("Enter the number of elements in the array: "); System.out.print("Enter the number of elements in the array: ");
int n = sc.nextInt(); 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++) { for (int i = 0; i < n; i++) {
a[i] = sc.nextInt(); a[i] = sc.nextInt();
}
System.out.print("Enter the target element to search for: ");
int t = sc.nextInt();
RecursiveBinarySearch<Integer> 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);
} }
System.out.print("Enter the target element to search for: ");
int t = sc.nextInt();
RecursiveBinarySearch<Integer> 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);
} }
} }