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 {
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);
// Transposition encryption
String transpositionInput = substitutionOutput.toString();
int modulus;
if ((modulus = transpositionInput.length() % n) != 0) {
modulus = n - modulus;
for (; modulus != 0; modulus--) {
transpositionInput += "/";
// Substitution encryption
StringBuffer substitutionOutput = new StringBuffer();
for (int i = 0; i < substitutionInput.length(); i++) {
char c = substitutionInput.charAt(i);
substitutionOutput.append((char) (c + 5));
}
}
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("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();
}
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);
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("Final encrypted text: ");
System.out.println(transpositionOutput);
// Substitution decryption
StringBuffer plaintext = new StringBuffer();
for (int i = 0; i < transpositionPlaintext.length(); i++) {
char c = transpositionPlaintext.charAt(i);
plaintext.append((char) (c - 5));
}
// 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);
}
}
System.out.println("Plaintext: ");
System.out.println(plaintext);
sc.close();
// 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();
}
}
}

View File

@ -2,9 +2,13 @@ package com.thealgorithms.datastructures.graphs;
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 @@ number between 0 and total number of vertices-1,both inclusive*/
/**
* @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 @@ number between 0 and total number of vertices-1,both inclusive*/
}
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++) {
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;
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) {
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()

View File

@ -11,21 +11,22 @@ import java.util.Stack;
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<Integer> stack = new Stack<Integer>();
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<Integer> stack = new Stack<Integer>();
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 @@ public class ReverseStack {
private static void insertAtBottom(Stack<Integer> 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);

View File

@ -10,61 +10,70 @@ import java.util.Scanner;
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];
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
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("The two non repeating elements are " + num1 + " and " + num2);
sc.close();
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
}
}
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.
*/
}

View File

@ -5,46 +5,47 @@ import java.util.*;
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 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 enter the initial elements
for (i = 0; i < size; i++) {
System.out.println("Enter the element");
a[i] = s.nextInt();
}
}
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];
// 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
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
// 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 class RecursiveBinarySearch<T extends Comparable<T>> extends SearchAlgori
}
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();
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);
}
}