instruction stringlengths 38 3.13k | output stringlengths 288 7.87k | __index_level_0__ int64 34 58.2k |
|---|---|---|
Create a web server in Java to handle multiple concurrent POST requests with heavy processing and large data payloads. Additionally, implement a custom encryption algorithm to encrypt and decrypt the data payloads before processing them. | To create a web server in Java to handle multiple concurrent POST requests with heavy processing and large data payloads, you can use the following steps:
Step 1: Set up the project
- Create a new Java project in your preferred IDE.
- Add the required dependencies, such as the Apache Tomcat server and any additional l... | 48,781 |
Write a Java program to calculate the area of a square given the length of a side. The program should also calculate and display the perimeter of the square. Additionally, you should implement error handling to handle cases where the user enters negative values for the length of the side. | Here is a Java program that calculates the area and perimeter of a square given the length of a side:
```java
import java.util.Scanner;
public class SquareCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the side:... | 48,869 |
Create a Java method that computes the factorial of a non-negative integer, but with the following additional requirements:
1. The method should use a recursive approach to calculate the factorial.
2. The method should handle negative input values by throwing an IllegalArgumentException with a meaningful error message... | Here is a Java method that meets all the requirements:
```java
public class FactorialCalculator {
public static long computeFactorial(long n) {
if (n < 0) {
throw new IllegalArgumentException("Input value must be non-negative");
}
if (n > 100) {
throw new ArithmeticE... | 48,888 |
Write a program in Java that removes all duplicate characters from a string and returns the remaining characters in the order they appear in the original string. Your program should only consider alphabetic characters (A-Z and a-z) and ignore any non-alphabetic characters. Additionally, the program should also ignore d... | Here is a Java program that removes duplicate characters from a string, considering only alphabetic characters and ignoring case:
```java
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
String input = "Hello, World!";
String ... | 48,921 |
Create a list of 10,000 strings in Java, but ensure that none of the strings have any repeating characters. | Here's an example code to create a list of 10,000 strings in Java, ensuring that none of the strings have any repeating characters:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class UniqueStringList {
private static final int LIST_SIZE = 10000;
private static fin... | 48,940 |
Write a Java code snippet to find the second smallest element in an array of integers. The array should be of size 100 and should be filled with random integers between 1 and 1000.
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (int) (Math.random() * 1000) + 1;
}
// Find the second smallest elem... | Here is a Java code snippet to find the second smallest element in an array of integers:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (int) (Math.random() * 1000) + 1;
... | 49,047 |
Generate a unique 20 digit alphanumeric ID using Java, where the alphanumeric characters can only be uppercase letters (A-Z) and the numbers (0-9). The ID should have at least 8 distinct letters and at least 8 distinct numbers. The ID should also have at least one uppercase letter and one number at the beginning and at... | Here is an example implementation in Java:
```java
import java.util.*;
public class UniqueIDGenerator {
public static void main(String[] args) {
String uniqueID = generateUniqueID();
System.out.println("Unique ID: " + uniqueID);
}
public static String generateUniqueID() {
String ... | 49,050 |
Write a method 'addString' in Java that takes two strings as parameters and returns a single string that concatenates the two strings. The method should also remove any duplicate characters in the resulting string, and the characters should be sorted in ascending order. Additionally, the method should ensure that all u... | Here is an example of how you can implement the 'addString' method in Java:
```java
import java.util.Arrays;
public class StringManipulator {
public static String addString(String str1, String str2) {
// Concatenate the two strings
String result = str1 + str2;
// Remove dupli... | 49,089 |
Implement a method in Java that calculates the memory size of a list of integers. The method should take a List<Integer> as input and return the size of the list in bytes. The size should include the memory occupied by the list itself, as well as the memory occupied by each individual integer in the list.
However, the... | Here is an implementation of the method that calculates the memory size of a list of integers, taking into consideration the memory occupied by referenced objects:
```java
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MemoryCalculator {
public... | 49,209 |
Write a Java program that takes a String as parameter and counts how many words are in it. However, you must exclude any words that contain consecutive vowels, and also words that start and end with the same letter. | Here's a Java program that takes a string as input and counts the number of words in it, excluding words that contain consecutive vowels and words that start and end with the same letter:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WordCount {
public static void ... | 49,290 |
Write a Java code to take a string as input and return the number of unique words present in it. Consider that words are separated by one or more spaces and punctuation marks should be ignored.
Example:
Input: "Hello, how are you? How are you doing today?"
Output: 6 (Hello, how, are, you, doing, today)
Note:
- Words ... | Here is one possible solution:
```java
import java.util.HashSet;
public class UniqueWordsCount {
public static int countUniqueWords(String input) {
// Convert the input string to lowercase
input = input.toLowerCase();
// Remove punctuation marks from the input string
input... | 49,463 |
Construct an algorithm to detect a cycle in a linked list, but you are not allowed to use additional space. Additionally, you are not allowed to modify the linked list in any way. | To detect a cycle in a linked list without using additional space or modifying the linked list, we can use the Floyd's Tortoise and Hare algorithm. This algorithm uses two pointers, one moving at a slower pace (tortoise) and another moving at a faster pace (hare), to detect if there is a cycle in the linked list.
Here... | 49,508 |
Create a switch statement that prints "Yay!" if input is 1, "Nay!" if input is 2, and "Oops!" if input is any other value. The input should be limited to integers between -100 and 100 (inclusive). | Here is the switch statement you requested:
```java
int input = ...; // Assign your input value here
switch (input) {
case 1:
System.out.println("Yay!");
break;
case 2:
System.out.println("Nay!");
break;
default:
System.out.println("Oops!");
break;
}
```
Ma... | 49,519 |
Implement a comparator method in Java to compare two objects of the same class. The comparison should be based on the country's population and area, with population taking priority. Additionally, the comparison should be case-insensitive for the country's name. The comparator should return a negative integer if the fir... | Here's an implementation of the comparator method in Java:
```java
import java.util.Comparator;
public class CountryComparator implements Comparator<Country> {
@Override
public int compare(Country c1, Country c2) {
if (c1 == null && c2 == null) {
return 0;
} else if (c1 == null) {... | 49,641 |
Write a Java program to insert a new node at a specified position in a circular linked list. The position should be provided as input by the user.
Additional Requirements:
1. The program should handle the case where the specified position is out of bounds (i.e., greater than the length of the list or negative) by eith... | Here is a possible implementation of the Java program to insert a new node at a specified position in a circular linked list:
```java
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class CircularLinkedList {... | 49,670 |
Write a Java program to remove comments from the Java program. However, your program should also handle nested comments properly.
Erroneous code:
public class HelloWorld {
/*
This is a multiline comment.
*/
/* public static void main(String[] args) {
System.out.println("Hello World!"); // This ... | Here is a Java program that removes comments from a Java program, handling nested comments and scenarios where comments are within string literals or within other valid syntax elements:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public clas... | 49,703 |
Generate a correct Java program to swap two given numbers without using any temporary variables. The program should also be able to swap two characters without using temporary variables. Additionally, the program should be able to swap two strings without using temporary variables. The time complexity of the program sh... | Here's a Java program that swaps two given numbers, characters, and strings without using any temporary variables and with a time complexity of O(1):
```java
public class Swap {
public static void main(String[] args) {
// Swap numbers
int a = 5;
int b = 10;
System.out.println("... | 49,724 |
Generate a Java program that prints the sum of digits of a given number.
However, the program should handle negative numbers, decimal numbers, and scientific notation as well.
For example, for the input -3.45e2, the program should output -12.
#Erroneous Code#
Generate a Java program that prints the sum of digits of a ... | Here's the corrected code:
```java
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scanner.nextLine();
double number = Double.parseDouble(inp... | 49,758 |
Create a Java class named "MyClass" with three methods - getName(), setName(), and displayName(). Additionally, implement a static variable called "counter" to keep track of the number of instances of "MyClass" that have been created. Increment the counter variable every time a new instance of "MyClass" is created and ... | Here is an example implementation of the MyClass class that meets the requirements:
```java
import java.time.Duration;
import java.time.LocalDateTime;
public class MyClass {
private static int counter = 0;
private LocalDateTime createdTime;
public MyClass() {
counter++;
createdTime = Loca... | 49,902 |
Write a Java method to remove all whitespaces and punctuation marks from a string, reverse the order of the remaining characters, and convert all letters to lowercase. | Here is a Java method that removes whitespaces and punctuation marks, reverses the order of the remaining characters, and converts all letters to lowercase:
```java
public static String modifyString(String input) {
// Remove whitespaces and punctuation marks
String modifiedString = input.replaceAll("[\\p{Punct... | 49,935 |
Write a Java program to get the day of the week from a given Date object, but do not use any built-in date or time libraries or classes. The program should consider leap years and should correctly calculate the day of the week for any given date from January 1, 1900, to December 31, 2100. | Here's a Java program that calculates the day of the week for any given date from January 1, 1900, to December 31, 2100, without using any built-in date or time libraries or classes:
```java
public class DayOfWeekCalculator {
public static void main(String[] args) {
int day = 1; // Day of the month (1-31)
... | 49,943 |
Create a Java program to find the median of an array of integers. However, you are not allowed to use any built-in methods or libraries to find the median. You must implement your own algorithm to calculate the median.
int[] arr = {1, 2, 3, 4, 5, 6, 7};
| Here is a Java program that finds the median of an array of integers without using any built-in methods or libraries:
```java
public class MedianCalculator {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
double median = calculateMedian(arr);
System.out.pri... | 49,990 |
Write a Java method called `binarySearch` that takes in an array of integers and a target integer, and returns the index of the target in the array if it exists, or -1 if it does not. The array is assumed to be sorted in ascending order.
Provide a time complexity analysis for the `binarySearch` method. | Here is the implementation of the `binarySearch` method:
```java
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid;
}... | 50,021 |
Create a Java method to print all elements in an array in reverse order without using any additional data structures or recursion. Additionally, ensure that the method has a time complexity of O(n), where n is the length of the array. | Here's a Java method that prints all elements in an array in reverse order without using any additional data structures or recursion:
```java
public static void printArrayReverse(int[] arr) {
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
}
```
Explanation:
- The method `pri... | 50,125 |
Create a class in Java that has three fields and three constructors.
Field1: String - this field should only accept input that consists of alphabetic characters and should be case-sensitive.
Field2: int - this field should only accept input that is within a specific range, for example, between 1 and 100 (inclusive).
F... | Here is an example of a class in Java that meets the given requirements:
```java
public class MyClass {
private String field1;
private int field2;
private boolean field3;
public MyClass(String field1, int field2, boolean field3) {
this.field1 = validateField1(field1);
this.field2 =... | 50,273 |
Implement a recursive algorithm in Java to count the number of ones in a binary number, without using any bitwise operations or loops. The input binary number will be a string of 0s and 1s with a maximum length of 10 characters. The algorithm should have a time complexity of O(n), where n is the length of the binary nu... | Here's a recursive algorithm in Java to count the number of ones in a binary number:
```java
public class CountOnes {
public static void main(String[] args) {
String binaryNumber = "1010101010"; // example binary number
int count = countOnes(binaryNumber);
System.out.println("Number of ones... | 50,326 |
Create a Java program to find all Armstrong numbers in a given range and display them in descending order.
An Armstrong number is a number that is equal to the sum of its digits raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.
Your program should take... | Here is the Java program to find all Armstrong numbers in a given range and display them in descending order:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArmstrongNumbers {
public static void main(String[] args) {
Scanner... | 50,332 |
Create a Java program to multiply two given matrices, ensuring that the dimensions of the matrices are not equal and that the number of columns in the first matrix is equal to the number of rows in the second matrix. The program should also handle the case where the matrices have dimensions greater than 1000. Additiona... | Here's a Java program that multiplies two given matrices using the divide-and-conquer approach:
```java
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the dimensions o... | 50,376 |
Create a class called "ProgrammingWorld" that prints out the following message: "Welcome to the world of programming!" Additionally, implement a method called "reverseString" that takes in a string as an argument and prints out the reverse of that string. The reverseString method should only use a maximum of three line... | Here is the implementation of the "ProgrammingWorld" class:
```java
public class ProgrammingWorld {
public static void main(String[] args) {
System.out.println("Welcome to the world of programming!");
}
public static void reverseString(String str) {
System.out.println(new StringBuilder... | 50,387 |
Write a Java program to display the area and circumference of a given circle, rounded to two decimal places.
The program should take the radius as input from the user.
Additionally, the program should validate that the radius is a positive number and not zero before calculating the area and circumference.
Furthermore, ... | Here is a Java program that meets all the requirements mentioned:
```java
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
String radiusInput = scanner.n... | 50,468 |
Write a Java program for binary search that operates on a sorted array of integers. The program should take an input array and a target integer as parameters and return the index of the target integer in the array. If the target integer is not found in the array, the program should return -1. The program should have a ... | Here is a Java program that implements the binary search algorithm with the specified requirements:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (ri... | 50,641 |
Create a class in Java for a rectangle shape with length and breadth as attributes. The rectangle should also have a method to calculate its area and perimeter. Additionally, the rectangle's length and breadth should be prime numbers, and the maximum length or breadth should not exceed 1000. | Here is an example of a Rectangle class in Java that meets the given requirements:
```java
import java.util.ArrayList;
public class Rectangle {
private int length;
private int breadth;
public Rectangle(int length, int breadth) {
if (isPrime(length) && isPrime(breadth) && length <= 1000 && breadth... | 50,688 |
Write a method to print the first n numbers in the Fibonacci series, where n is a positive integer input by the user.
Additional requirements:
1. Implement the method recursively.
2. Handle edge cases where n is less than or equal to 0.
3. Optimize the method to have a time complexity of O(log n).
4. Use memoization t... | Here is a method in Java that meets all the requirements:
```java
import java.util.HashMap;
import java.util.Map;
public class FibonacciSeries {
private static Map<Integer, Integer> memo = new HashMap<>();
public static void main(String[] args) {
int n = 10;
printFibonacciSeries(n);
... | 50,709 |
Create a script in Java that builds a string based on a given character repeated n number of times, ensuring that the resulting string has a length greater than or equal to 10. The character can be any printable ASCII character. The number of repetitions should be between 3 and 10 (inclusive). Additionally, the script ... | Here is an example script in Java that builds a string based on a given character repeated n number of times, ensuring that the resulting string has a length greater than or equal to 10. It also calculates the sum of the ASCII values of all characters in the resulting string:
```java
import java.util.Random;
public c... | 50,736 |
Write a Java program to find out the longest word from a sentence, but with a time complexity of O(nlogn). In addition, the program should also handle cases where there are multiple words with the same length, and return all of them.
String sentence = "This is a sample sentence"
Expected Output: "sentence" | Here is a Java program that finds the longest word from a sentence with a time complexity of O(nlogn):
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LongestWord {
public static void main(String[] args) {
String sentence = "This is a sample sentence";
... | 50,822 |
Write a Java program to compare two strings and determine if they are equal. The program should also check if the two strings are anagrams of each other. Additionally, the program should calculate the Damerau-Levenshtein distance between the two strings, which is the minimum number of single-character edits (insertions... | Here's a Java program that compares two strings, checks if they are anagrams, and calculates the Damerau-Levenshtein distance between them:
```java
import java.util.Arrays;
public class StringComparison {
public static boolean areEqual(String str1, String str2) {
return str1.equals(str2);
}
publi... | 50,853 |
Create a Java program that compares two strings and checks if they are equal or not. The program should ignore case sensitivity while comparing the strings. Additionally, the program should also print the number of characters present in each string.
String s1 = "Hello";
String s2 = "world";
// Erroneous code
int num... | Here's the corrected code:
```java
public class StringComparison {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "world";
int numChars1 = s1.length();
int numChars2 = s2.length();
boolean equal = s1.equalsIgnoreCase(s2); // comparing the strings ... | 50,877 |
Write a Java program to print the Fibonacci sequence starting from a given number.
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. The sequence starts with 0 and 1.
In this program, we will take a starting number from the user and generate the Fibonacci sequenc... | Here's the corrected Java program to print the Fibonacci sequence starting from a given number:
```java
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the starting number: ");
... | 50,915 |
Construct an array of size N in Java and initialize each element to a randomly generated integer between 1 and 1000. The value of N will be provided as an input. | Here is an example of how you can construct an array of size N and initialize each element with a randomly generated integer between 1 and 1000 in Java:
```java
import java.util.Random;
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
Scanner scanner = new Scan... | 50,933 |
Construct a class in Java that has two methods called 'sayHello' and 'sayGoodbye'. The 'sayHello' method should take in a String parameter and print out "Hello, {parameter}!" The 'sayGoodbye' method should take in an integer parameter and print out "Goodbye, {parameter}!". Additionally, the class should keep track of t... | Here is an implementation of the class in Java:
```java
public class GreetingCounter {
private int helloCount;
private int goodbyeCount;
public GreetingCounter() {
helloCount = 0;
goodbyeCount = 0;
}
public void sayHello(String name) {
if (name.matches("[a-zA-Z]+")... | 50,947 |
Write a method to find all duplicate elements in an array of integers, where each element is in the range from -10^9 to 10^9, and return them in ascending order.
Additional requirements:
1. Your method should have a time complexity of O(n).
2. Your method should use constant space, i.e., it should not create any addit... | Here is a possible implementation of the method in Java:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DuplicateFinder {
public static int[] findDuplicates(int[] nums) {
if (nums == null || nums.length < 2) {
return new int[0];
}
... | 50,969 |
Create a class that detects if a given String contains the longest palindrome substring. The class should return the length of the longest palindrome substring found. The algorithm should have a time complexity of O(n^2) and a space complexity of O(1).
Additionally, the algorithm should be able to handle inputs with s... | Here is an implementation of the class in Java:
```java
public class LongestPalindromeSubstring {
public static int findLongestPalindromeSubstring(String str) {
if (str == null || str.length() == 0) {
return 0;
}
// Remove whitespace and non-alphanumeric characters
... | 51,078 |
Implement a method in Java to reverse a number. The number can be positive or negative. The reversed number should have the same sign as the original number.
In addition to reversing the number, your method should also remove any leading zeros. For example, if the original number is 100, the reversed number should be ... | Here's an implementation of the method to reverse a number in Java:
```java
public class ReverseNumber {
public static int reverseNumber(int num) {
boolean isNegative = num < 0;
num = Math.abs(num); // make the number positive
int reverse = 0;
while (num != 0) {
... | 51,129 |
Write a code in Java to sort a given list of integers in ascending order. The list may contain duplicate elements. The time complexity of the sorting algorithm should be O(n log n) and the space complexity should be O(1). | One way to achieve O(n log n) time complexity and O(1) space complexity is by using the merge sort algorithm. Here's the code:
```java
import java.util.List;
public class IntegerSorter {
public static void mergeSort(List<Integer> list) {
if (list.size() > 1) {
int mid = list.size() / 2;
... | 51,174 |
Create a class in Java which stores the details of a book (title, author, ISBN) and also keeps track of the number of times the book has been borrowed.
Additionally, implement a method to calculate the average rating of the book based on a list of user ratings (ranging from 1 to 5). The method should return the averag... | Here is a possible implementation of the book class:
```java
import java.util.ArrayList;
import java.util.List;
public class Book {
private String title;
private String author;
private String ISBN;
private int borrowCount;
private List<Review> reviews;
private int totalPages;
private int c... | 51,352 |
Write a Java method to check if a string is a palindrome, considering only alphanumeric characters and ignoring case. Additionally, the method should handle special characters and white spaces by removing them before performing the palindrome check.
string = "A man, a plan, a canal, Panama!" | Here's a Java method that checks if a string is a palindrome, considering only alphanumeric characters and ignoring case:
```java
public static boolean isPalindrome(String str) {
// Remove special characters and white spaces
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Check if... | 51,449 |
Create a customer class in Java that can be used to store information about customers.
Create a class with field names: id (integer), firstName (text), lastName (text), email (text), address (text)
In addition to the fields mentioned above, add the following fields to the customer class:
- phoneNumber (text)
- dateOfB... | Here is the implementation of the Customer class in Java:
```java
public class Customer {
private int id;
private String firstName;
private String lastName;
private String email;
private String address;
private String phoneNumber;
private String dateOfBirth;
private String gender;
... | 51,461 |
Implement a Java code to print the first 15 multiples of a given number, but only if the number is divisible by both 3 and 5. | Here is a Java code that prints the first 15 multiples of a given number, but only if the number is divisible by both 3 and 5:
```java
import java.util.Scanner;
public class MultiplesOfNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Ent... | 51,491 |
Create a Java program to take an integer input from the user within the range of 1 to 20 (inclusive) and print its factorial. The program should handle the case when the input is out of range by displaying an appropriate error message. Additionally, implement the factorial calculation using recursion instead of iterati... | Here's a Java program that meets your requirements:
```java
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 20: ");
int number = scanner.nextInt(... | 51,713 |
Create a Java class to represent a new type of vehicle called hovercar, which can only be powered by a specific type of energy called "ion fuel" and has a maximum speed of 500 km/h. Additionally, the hovercar should have the ability to levitate at a certain height above the ground, with the height being adjustable by t... | Here's an example implementation of the Hovercar class in Java:
```java
public class Hovercar {
private static final String POWER_SOURCE = "ion fuel";
private static final int MAX_SPEED = 500; // km/h
private static final int MIN_ALTITUDE = 1; // meters
private static final int MAX_ALTITUDE = 10; // me... | 51,716 |
Write a Java program to generate a schedule for students with a given set of available IDs and a specified maximum number of courses per student. Each course has a unique ID, title, instructor, and meeting time. The program should allow students to select their desired courses from a list of available courses and creat... | Here is a Java program that implements the features mentioned above:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
class Course {
private String id;
private String title;
private String instructor;
private String me... | 51,732 |
Write a Java program that generates 5 random numbers between 1 and 100, inclusive, and stores them in an array. The program should then sort the array in ascending order and display the sorted numbers. Additionally, the program should ensure that no duplicate numbers are generated and display an error message if duplic... | Here is a Java program that generates 5 random numbers between 1 and 100, stores them in an array, checks for duplicate numbers, sorts the array in ascending order, and displays the sorted numbers:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class R... | 51,760 |
Construct a nested for loop to access each element of the given 2D array. However, instead of accessing each element sequentially, you need to access the elements in a zigzag pattern. | Here's an example of a nested for loop that accesses each element of a 2D array in a zigzag pattern:
```java
int[][] array = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
int rows = array.length;
int columns = array[0].length;
for (int i = 0; i < rows; i++) {
// For even rows, access ... | 51,768 |
Create a Java program to print out factorials from 1 to 10, but with the following restrictions:
1. You are not allowed to use any loops, recursion, or mathematical operators (*, /, +, -) to calculate the factorials.
2. You must implement the factorial calculation using bitwise operations only.
3. The program must hand... | Here's a Java program that satisfies the given restrictions and calculates the factorials using bitwise operations only:
```java
public class FactorialCalculator {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
try {
int factorial = calculateFactorial(i... | 51,871 |
Write a program in Java to check if a number is a prime number. A prime number is an integer greater than 1 that is only divisible by 1 and itself.
Additionally, include a method called "isPrimeFast" that improves the efficiency of the algorithm by implementing the Sieve of Eratosthenes. The "isPrimeFast" method shou... | Here is the code to check if a number is prime and the reference implementation of the "isPrimeFast" method with a mistake:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PrimeNumberChecker {
public s... | 51,938 |
Write a Java class that implements a binary search algorithm to search for a specific element in an array of integers. The class should also include a method to sort the array in ascending order before performing the search. The class should be able to handle arrays with a maximum length of 10^6.
Additionally, the cla... | Here is the Java class that implements a binary search algorithm to search for a specific element in an array of integers:
```java
import java.util.Arrays;
public class BinarySearch {
private int[] array;
public BinarySearch(int[] array) {
this.array = array;
}
public int[] sortArray() {
... | 51,961 |
Create a Java program to sort an array of integers using the Gnome Sort technique. The Gnome Sort algorithm is similar to the Selection Sort algorithm, but instead of finding the minimum element and swapping it with the first unsorted element, it finds the first unsorted element and swaps it with the previous element u... | Here's a Java program that implements the Gnome Sort algorithm to sort an array of integers:
```java
public class GnomeSort {
public static void gnomeSort(int[] arr) {
int index = 0;
while (index < arr.length) {
if (index == 0 || arr[index] >= arr[index - 1]) {
... | 51,976 |
Write a Java program to display a pyramid with the given height. The height can be positive or negative, and the program should handle both cases.
#New Test# | Here's the Java program to display a pyramid with the given height:
```java
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the height of the pyramid: ");
int height = scanner.nextIn... | 52,006 |
Write Java code to create a class called Card with two string fields, rank and suit. The rank should only be one of the following values: "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King". The suit should only be one of the following values: "Hearts", "Diamonds", "Clubs", "Spades". The Card c... | Here is the Java code for the Card class:
```java
public class Card {
private String rank;
private String suit;
public Card(String rank, String suit) {
this.rank = rank;
this.suit = suit;
}
public int getValue() {
if (rank.equals("Ace")) {
return 1;
} e... | 52,040 |
Create an object of type Car in Java that has a maximum speed of 200 km/h and can only be instantiated with a non-negative fuel capacity in liters, where the fuel capacity must be greater than or equal to 30 liters. Additionally, the fuel capacity should be a multiple of 10 liters. | Here's an example of a Car class in Java that meets the specified requirements:
```java
public class Car {
private int maxSpeed;
private int fuelCapacity;
public Car(int fuelCapacity) {
this.maxSpeed = 200;
// Check if fuel capacity is non-negative and a multiple of 10
if (fuelCap... | 52,087 |
Implement a breadth-first search algorithm to find the shortest path between two nodes in a weighted graph in Java. Additionally, modify the algorithm to consider edge weights as well as node distances when calculating the shortest path. | Sure! Here's an implementation of a modified breadth-first search (BFS) algorithm that considers both edge weights and node distances to find the shortest path between two nodes in a weighted graph in Java:
```java
import java.util.*;
public class ShortestPath {
private static class Node implements Comparable<Nod... | 52,111 |
Create a thread-safe Java method that increments a given counter by a randomly generated value between 1 and 1000 and then checks if the counter value is a prime number. | Here is a thread-safe Java method that increments a given counter by a randomly generated value between 1 and 1000 and then checks if the counter value is a prime number:
```java
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private static final AtomicInteger co... | 52,218 |
Implement a doubly linked list structure with the following methods using Java:
1. insertFront(int value): Inserts a node with the given value at the front of the list.
2. insertEnd(int value): Inserts a node with the given value at the end of the list.
3. insertAfter(int insertValue, int afterValue): Inserts a node wi... | Here is the implementation of the doubly linked list structure in Java:
```java
public class DoublyLinkedList {
private Node head;
private Node tail;
private int length;
private class Node {
private int data;
private Node prev;
private Node next;
public Node(int data) ... | 52,240 |
Write a Java program that takes in 3 strings, each containing at most 50 characters, and combines them into one in reverse order. The program should reverse the order of the characters within each string before combining them. Additionally, the program should remove any duplicate characters in the final combined string... | Here is a possible implementation of the Java program:
```java
import java.util.HashSet;
public class ReverseAndCombineStrings {
public static void main(String[] args) {
String string1 = "hello";
String string2 = "world";
String string3 = "!";
String combinedString = reverseAndCom... | 52,286 |
Construct a for loop in Java for iterating through a 2D array and print out each element, but only print out the elements that are prime numbers.
The time complexity requirement for this question is O(n^2), where n is the size of the 2D array. | Here is an example of a for loop in Java that iterates through a 2D array and prints out each element that is a prime number:
```java
int[][] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int num = array[i][j];
... | 52,299 |
Write some Java code to fill in an array of size n with all prime numbers from 1 to n, where n is an odd number. Additionally, you should implement the code in a way that minimizes the time complexity. | Here is a Java code that fills an array of size n with all prime numbers from 1 to n, where n is an odd number. The code is implemented using the Sieve of Eratosthenes algorithm, which minimizes the time complexity.
```java
import java.util.Arrays;
public class PrimeNumbers {
public static void main(String[] args... | 52,314 |
Write a Java program that takes a string as an argument, reverses the string, and prints it out. The program should also count the number of vowels in the reversed string and display the result.
Additionally, the program should handle any input errors, such as null input or input that is not a valid string. If the inp... | Here's a Java program that fulfills the requirements mentioned:
```java
public class ReverseString {
public static void main(String[] args) {
String input = "Hello, World!";
try {
String reversedString = reverseString(input);
System.out.println("Reversed string: " + reversed... | 52,328 |
Construct a switch statement to check if a month name is valid. Additionally, handle the case sensitivity of the input and consider the possibility of the input containing leading or trailing whitespace characters. Furthermore, the month name should only be considered valid if it matches a specific set of names, which ... | Here is an example of how you can construct a switch statement to check if a month name is valid, considering case sensitivity, leading/trailing whitespace characters, and a specific set of names:
```java
String month = " january "; // Example month input
// Trim leading and trailing whitespace characters
month =... | 52,335 |
Create a Spring boot program to find the area of a triangle given the lengths of its three sides, which are decimal numbers.
Additional requirements:
- The program should validate whether the given lengths form a valid triangle (i.e., the sum of any two sides should be greater than the third side) and display an appro... | Here is an example of a Spring Boot program that meets the given requirements:
```java
import java.util.Scanner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TriangleAreaCalculator {
public static void... | 52,344 |
Write a multi-threaded application that calculates the sum of all prime numbers up to a given limit. The application should use a thread pool with a maximum size of 5 to divide the work among multiple threads for increased performance. Each thread should maintain a separate counter to keep track of the number of prime ... | Here's an example implementation of a multi-threaded application that calculates the sum of all prime numbers up to a given limit using a thread pool with a maximum size of 5:
```java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Exe... | 52,345 |
Create a Java program that removes duplicate elements from an array and sorts the remaining elements in ascending order. The program should also keep track of the number of times each unique element occurs in the array and display the frequency of each element after removing duplicates. The program should have a time c... | Here is a Java program that meets the given requirements:
```java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class RemoveDuplicatesAndSort {
public static void main(String[] args) {
int[] array = {5, 3, 2, 5, 4, 3, 1, 2, 4, 5}; // Sample input array
int[] ... | 52,433 |
Create a class in Java that represents a bank account. The class should have the following private variables: accountNumber (String), accountHolderName (String), accountBalance (double), and isActive (boolean).
The class should have a constructor that takes in the accountNumber and accountHolderName as parameters and... | Here is the implementation of the BankAccount class in Java:
```java
public class BankAccount {
private String accountNumber;
private String accountHolderName;
private double accountBalance;
private boolean isActive;
public BankAccount(String accountNumber, String accountHolderName) {
this... | 52,612 |
Create a Java method that takes a decimal number as an argument and returns its binary equivalent. The method should have a time complexity of O(log n), where n is the absolute value of the decimal number. Additionally, you should handle negative decimal numbers and throw a custom exception if the input is not a valid ... | Here is an implementation of a Java method that takes a decimal number as an argument and returns its binary equivalent:
```java
public class DecimalToBinaryConverter {
public static class InvalidDecimalNumberException extends Exception {
public InvalidDecimalNumberException(String message) {
s... | 52,633 |
Write a Java program to find all pairs of integers from an array whose sum equals a given number, but with the additional constraint that each integer can only be used once in a pair. Additionally, the program should optimize for time complexity.
#Explanation#
In the given test, the task is to find pairs of integers f... | Here is a Java program that finds all pairs of integers from an array whose sum equals a given number, while also ensuring that each integer is used only once in a pair:
```java
import java.util.HashMap;
public class PairSum {
public static void findPairs(int[] arr, int targetSum) {
// Create a HashMap to... | 52,706 |
Write a stack class in Java that supports the following additional operations:
1. `getMinimum()`: Returns the minimum element in the stack in constant time.
2. `getMaximum()`: Returns the maximum element in the stack in constant time.
3. `getMedian()`: Returns the median element in the stack in constant time.
4. `getMo... | Here is an implementation of the stack class in Java that supports the additional operations mentioned:
```java
import java.util.*;
class StackWithAdditionalOperations<T extends Comparable<T>> {
private Stack<T> stack;
private TreeSet<T> distinctElements;
public StackWithAdditionalOperations() {
... | 52,725 |
Write a code in Java to print out the first 5 prime numbers greater than the given number, while ensuring the output is in ascending order and each number is separated by a comma.
Number: 10 | Here's a code that satisfies the requirements:
```java
public class Main {
public static void main(String[] args) {
int number = 10;
int count = 0;
int currentNumber = number + 1;
while (count < 5) {
if (isPrime(currentNumber)) {
System.out.print(current... | 52,794 |
Write a Java program that gathers the source code of a web page, using only built-in Java libraries, and retrieve specific elements from the page. The program should also handle potential exceptions that may occur during the process. The URL of the web page should be passed as a command line argument to the program, an... | Here's a Java program that uses built-in Java libraries to gather the source code of a web page and retrieve specific elements from it. It handles potential exceptions that may occur during the process. You can pass the URL of the web page as a command line argument and specify the specific element to retrieve as an ad... | 52,864 |
Construct a switch statement for the given pseudo-code to determine the type of day based on the given day of the week.
1. Initialize a variable "day" with the given day of the week.
2. Use a switch statement with "day" as the expression.
3. Inside the switch statement, add cases for each day of the week (Sunday to Sat... | Here is the switch statement for the given pseudo-code:
```java
// Step 1: Initialize a variable "day" with the given day of the week
String day = "Sunday"; // Example day of the week
// Step 2: Use a switch statement with "day" as the expression
switch (day) {
// Step 3: Add cases for each day of the week (Sunda... | 52,937 |
Create a Java program to print out the multiplication table for the first 100 prime numbers, where each row and column should be sorted in ascending order. Additionally, the program should only use a single loop for generating the prime numbers. | Here is a Java program that prints out the multiplication table for the first 100 prime numbers, using a single loop to generate the prime numbers:
```java
public class PrimeMultiplicationTable {
public static void main(String[] args) {
int count = 0;
int number = 2;
int[] primes = new int[... | 52,973 |
Create a Java program that checks if a given string has any special characters and returns the count of each special character found in the string. Special characters are defined as any non-alphanumeric characters (excluding spaces) and common punctuation marks.
For example, given the string "This is a string!", the p... | Here's the Java program that checks if a given string has any special characters and returns the count of each special character found in the string:
```java
public class SpecialCharacterCounter {
public static void main(String[] args) {
String str = "This is a string!";
int[] specialCharCount = co... | 53,045 |
Create two classes 'Circle' and 'Rectangle' in Java which print the circumference and area of their respective shapes.
1. The 'Circle' class should have the following attributes and methods:
- Attributes: radius (double)
- Methods:
- getRadius(): returns the radius of the circle
- setRadius(double rad... | Here is the updated code:
```java
import java.text.DecimalFormat;
abstract class Shape {
abstract double getPerimeter();
abstract double getArea();
abstract void printDetails();
abstract void printShapeName();
}
class Circle extends Shape {
private double radius;
public double getRadius() {
... | 53,076 |
Generate a Java program to sort an array of n elements in ascending order using the merge sort algorithm. The program should have a time complexity of O(n log n) and should be able to handle large arrays of up to 10^6 elements efficiently. Additionally, the program should implement multithreading to further optimize th... | Sure! Here's a Java program that implements the merge sort algorithm to sort an array in ascending order using multithreading:
```java
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MergeSortMultithreaded ... | 53,103 |
Write a Java code to create multiple threads, where each thread performs a specific task. Each task should involve multiple steps and require complex logical reasoning. The code should ensure that the threads are synchronized and communicate with each other using shared memory. Additionally, each thread should have a p... | Here's an example Java code that demonstrates creating multiple threads, each performing a specific task with multiple steps and using shared memory for communication. It also implements a priority-based scheduling algorithm to determine the order of execution.
```java
import java.util.concurrent.locks.Lock;
import ja... | 53,302 |
Create a method in Java that takes an array of integers and finds the maximum value that is divisible by 3, 5, and 7. | Here is an example of a Java method that takes an array of integers and finds the maximum value that is divisible by 3, 5, and 7:
```java
public class MaximumDivisible {
public static int findMaximumDivisible(int[] arr) {
int maxDivisible = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {... | 53,317 |
Create a JavaFX program that allows a user to move a square shape in 3 different directions using the arrow keys. Additionally, implement collision detection to prevent the square from overlapping with any other shapes on the screen. The collision detection should be optimized for handling hundreds of shapes on the scr... | Sure! Here's an example of a JavaFX program that allows the user to move a square shape using arrow keys and implements collision detection to prevent overlapping with other shapes on the screen. It uses an optimized approach using a quadtree data structure for efficient collision detection.
```java
import javafx.appl... | 53,319 |
Create a Java class with an empty constructor and a parameterized constructor. The parameterized constructor should have at least three parameters of different data types. Additionally, one of the parameters should be an array of objects. | Here is an example of a Java class with an empty constructor and a parameterized constructor that meets the given requirements:
```java
public class MyClass {
private int intValue;
private String stringValue;
private Object[] objectArray;
// Empty constructor
public MyClass() {
// Code... | 53,331 |
Write a Java program that takes an array of integers and prints the numbers that are divisible by both 5 and 7, while excluding any numbers that are also divisible by 3. | Here is a Java program that accomplishes the task:
```java
public class DivisibleByFiveAndSeven {
public static void main(String[] args) {
int[] numbers = {10, 15, 21, 35, 42, 50, 63, 70, 105};
System.out.println("Numbers divisible by both 5 and 7 (excluding multiples of 3):");
for (int nu... | 53,332 |
Implement a data structure in Java that implements a stack with the following methods: 'push', 'pop', 'peek', 'isEmpty', and 'getSize'. The 'getSize' method should return the number of elements currently in the stack. Additionally, the implementation should throw a custom exception called 'StackUnderflowException' if '... | Here's an implementation of a stack data structure in Java that fulfills all the given requirements:
```java
public class Stack {
private int[] data;
private int top;
private int size;
public Stack() {
data = new int[100];
top = -1;
size = 0;
}
public void push(int val... | 53,345 |
Write a method to implement binary search using Java. Your implementation should also handle cases where the array is not sorted in ascending order. Additionally, you need to handle cases where the array contains duplicate elements. | Here is a Java implementation of the binary search algorithm that can handle cases where the array is not sorted in ascending order and contains duplicate elements:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;... | 53,357 |
Write a multi-threaded RabbitMQ consumer in Java to listen to a particular queue and process the messages concurrently.
Requirements:
1. The consumer should be able to handle a large number of incoming messages without blocking or slowing down the processing.
2. The consumer should use thread pooling to process the me... | Here is an example implementation of a multi-threaded RabbitMQ consumer in Java that meets the given requirements:
```java
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class RabbitMQConsumer {
private static fina... | 53,412 |
Generate a random 20-digit id in Java. | Here is a Java code snippet that generates a random 20-digit ID:
```java
import java.util.Random;
public class RandomIdGenerator {
public static void main(String[] args) {
Random random = new Random();
long id = random.nextLong();
String idString = String.valueOf(id);
if (idString.... | 53,421 |
Write a Java program to find the maximum element in a two dimensional array. The array should have at least 5 rows and 5 columns. The maximum element should be greater than 100. Return -1 if no such element exists.
int[][] matrix = {{101, 102, 103, 104, 105}, {106, 107, 108, 109, 110}, {111, 112, 113, 114, 115}, {116, ... | Here is a possible solution to the problem:
```java
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{101, 102, 103, 104, 105},
{106, 107, 108, 109, 110},
{111, 112, 113, 114, 115},
{116, 117, 118, 119, 120},
{12... | 53,489 |
Implement a queue data structure in Java using a circular linked list. The queue should support the following operations:
- enqueue(element): Insert an element to the back of the queue.
- dequeue(): Remove and return the element from the front of the queue.
- peek(): Return the element at the front of the queue without... | Here's an implementation of a queue data structure in Java using a circular linked list:
```java
public class CircularQueue {
private Node front, rear;
private int capacity, size;
// Node class to represent individual nodes in the circular linked list
private class Node {
int data;
No... | 53,632 |
Create a switch-case statement for a shopping cart to print out the items, their prices, and the quantity of each item. Each item should also have a unique identifier. The total cost of the shopping cart should be calculated and displayed at the end. The program should also allow the user to add or remove items from th... | Here's an example of how you can create a switch-case statement for a shopping cart program:
```java
import java.util.Scanner;
public class ShoppingCart {
public static void main(String[] args) {
// Declare and initialize the variables for items and their quantities
int item1Quantity = 2;
... | 53,731 |
Write a multithreaded program in Java that simulates a bank with multiple ATMs. Each ATM is represented by a separate thread and can perform transactions such as withdrawal, deposit, and balance inquiry concurrently with other ATMs. The program should ensure thread safety and handle synchronization issues using appropr... | Here's a multithreaded program in Java that simulates a bank with multiple ATMs, handles transaction cancellation, and ensures thread safety and synchronization using locks:
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Bank {
private double balance;
pr... | 53,748 |
Generate a Java program to find the kth largest element in a given unsorted array. The program should also return the index of the kth largest element. Additionally, the program should handle arrays of any size and should have a time complexity of O(nlogk) or better. | Here is a Java program that finds the kth largest element in an unsorted array and returns its index, with a time complexity of O(nlogk) or better:
```java
import java.util.PriorityQueue;
public class KthLargestElement {
public static void main(String[] args) {
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, ... | 53,769 |
Create a method that computes the sum of squares of all the even numbers from 0 up to n, where n is a positive integer. Additionally, ensure that the method only uses a single loop to identify the even numbers and calculate their sum of squares. n = 10 | Here is an example of a method in Java that computes the sum of squares of all the even numbers from 0 up to n using a single loop:
```java
public static int sumOfSquaresOfEvenNumbers(int n) {
int sum = 0;
for (int i = 0; i <= n; i += 2) {
sum += i * i;
}
return sum;
}
```
You can call this me... | 53,817 |
Write a class with a method named 'helloWorld' that takes in a string parameter and returns the string with all vowels replaced by the corresponding vowel's next letter in the alphabet. The method should also convert all uppercase letters in the input string to lowercase before performing the vowel replacement. The inp... | Here is an example of a class with the 'helloWorld' method that fulfills the given requirements:
```java
public class VowelReplacer {
public String helloWorld(String input) {
input = input.toLowerCase();
String result = "";
for (int i = 0; i < input.length(); i++) {
char c = inp... | 53,869 |
Generate a random 4x4 array using Java. The array should contain only unique prime numbers ranging from 1 to 16. | Here is a Java code that generates a random 4x4 array containing unique prime numbers ranging from 1 to 16:
```java
import java.util.Arrays;
import java.util.Random;
public class RandomPrimeArray {
public static void main(String[] args) {
int[][] array = generateRandomPrimeArray(4, 4);
fo... | 53,927 |
Create a new Java program that prints out all the prime numbers between 2 and 1000, but without using any built-in methods or libraries for prime number generation or checking. Your algorithm must be optimized to run in O(sqrt(n)) time complexity, where n is the input number being checked. Additionally, your program sh... | Here is a Java program that prints out all the prime numbers between 2 and 1000, optimized to run in O(sqrt(n)) time complexity:
```java
public class PrimeNumberGenerator {
public static void main(String[] args) {
int start = 2;
int end = 1000;
printPrimeNumbers(start, end);
}
... | 53,976 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.