instruction stringlengths 38 3.13k | output stringlengths 288 7.87k | __index_level_0__ int64 34 58.2k |
|---|---|---|
Write a Java program that takes in two strings as input and compares them without considering the case sensitivity and whitespace characters. The program should return true if the strings are equal and false otherwise. Provide an example of how you would use this program to compare two strings. | Here is an example Java program that compares two strings without considering the case sensitivity and whitespace characters:
```java
public class StringComparator {
public static boolean compareStrings(String str1, String str2) {
// Removing whitespace characters from the strings
str1 = str1.repla... | 13,645 |
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's a Java method that meets all the given requirements:
```java
public class DecimalToBinary {
public static class InvalidDecimalException extends Exception {
public InvalidDecimalException(String message) {
super(message);
}
}
public static String decimalToBinary(... | 13,659 |
Write a Java program to find all pairs of distinct 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 both time and space complexity.
#Explanation#
In this test, the task is to find ... | Here is a Java program that solves the given problem with optimal time and space complexity:
```java
import java.util.HashSet;
public class PairSum {
public static void findPairs(int[] arr, int targetSum) {
HashSet<Integer> seen = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
... | 13,727 |
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 a stack class in Java that supports the additional operations mentioned:
```java
import java.util.*;
public class StackWithAdditionalOperations<T extends Comparable<T>> {
private Stack<T> stack;
private TreeMap<T, Integer> frequencyMap;
private int distinctCount;
private i... | 13,748 |
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. Additionally, the code should calculate the sum of the digits of each prime number and print the sum along with the number itself.
Number: 1... | Here is the code in Java that meets the given requirements:
```java
public class PrimeNumbers {
public static void main(String[] args) {
int givenNumber = 10;
int count = 0;
int num = givenNumber + 1;
String primes = "";
while (count < 5) {
if (isPrime(n... | 13,811 |
Create a Java class for representing a student object that includes the following:
- The student object should have a unique identifier, which is a combination of their student ID, a randomly generated alphanumeric code, and a 10-character long hash value.
- The student object should have a first name, last name, middl... | Here is a possible implementation of the Java class for representing a student object:
```java
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Student {
private String studentId;
private String uniqueIdentifier;
private String firstName;... | 13,998 |
Write a Java program that creates two arrays and prints out the difference in number of elements between them. However, you should now implement a logic to handle the scenario where the first array is larger than the second array and vice versa. Additionally, handle the scenario where both arrays have the same number o... | Here is the Java program that implements the logic described above:
```java
public class ArrayDifference {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {2, 4, 6};
int difference;
if (arr1.length > arr2.length) {
difference = ar... | 14,058 |
Create a Java program that checks if a given string is a palindrome and returns the longest palindrome substring found in the string. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, ignoring spaces, punctuation, and capitalization.
For example, given th... | Here is the Java program that checks if a given string is a palindrome and returns the longest palindrome substring found in the string:
```java
public class PalindromeChecker {
public static void main(String[] args) {
String input = "Madam Arora teaches malayalam level";
String longestPalindr... | 14,064 |
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^9 elements efficiently. Additionally, the program should implement multithreading with a maximum of 8 th... | Here's an implementation of the merge sort algorithm in Java that meets all the given requirements:
```java
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MergeSortMultithreaded {
private static Execut... | 14,119 |
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 code that meets the requirements mentioned above:
```java
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
class Task implements Runnable {
private static final ReentrantLock lock = new ReentrantLock();
private static final int... | 14,328 |
Create a method in Java that takes an array of positive integers (greater than 1) and finds the maximum value that is divisible by 3, 5, and 7, while also being a prime number. | Here's a method in Java that takes an array of positive integers and finds the maximum value that is divisible by 3, 5, and 7, while also being a prime number:
```java
import java.util.Arrays;
public class MaxDivisiblePrime {
public static void main(String[] args) {
int[] numbers = {10, 15, 21, 25, 30, 35... | 14,331 |
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 thousands of shapes on the sc... | Here's a JavaFX program that allows the user to move a square shape using the arrow keys and implements collision detection to prevent overlapping with other shapes on the screen. The program also supports dynamic resizing of the square shape based on user input.
```java
import javafx.application.Application;
import j... | 14,341 |
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. The array should have a minimum length of 5 and each object within the array shou... | Here's an example of a Java class that meets the requirements:
```java
import java.util.Arrays;
public class MyClass {
private Object[] myArray;
public MyClass() {
// Empty constructor
}
public MyClass(Object[] array, int intValue, double doubleValue) {
this.myArray = array;
... | 14,345 |
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. The program should also calculate the sum of all the numbers that meet the above conditions, and return the result. Additionally, the program should ... | Here's a Java program that fulfills the requirements:
```java
public class DivisibleByFiveAndSeven {
public static void main(String[] args) {
int[] numbers = { 10, 15, 21, 30, 35, 42, 45, 50, 63, 70 };
int sum = 0;
int count = 0;
System.out.println("Numbers divisible by both 5 and ... | 14,346 |
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 is an implementation of the requested data structure in Java:
```java
public class Stack {
private CustomObject[] stackArray;
private int top;
private int size;
public Stack() {
stackArray = new CustomObject[50];
top = -1;
size = 0;
}
public void push(CustomObject... | 14,358 |
Write a method to implement binary search using Java. Your implementation should handle cases where the array is not sorted in ascending order and contains duplicate elements. Additionally, your implementation should have a time complexity of O(log n), where n is the size of the array. | Here is an implementation of binary search in Java that handles cases where the array is not sorted in ascending order and contains duplicate elements. This implementation has a time complexity of O(log n), where n is the size of the array.
```java
public class BinarySearch {
public static int binarySearch(int[] a... | 14,374 |
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's an example implementation of a multi-threaded RabbitMQ consumer in Java that fulfills the given requirements:
```java
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class... | 14,426 |
Write a Java program to find the maximum element in a two dimensional array. The array should have at least 10 rows and 10 columns. The maximum element should be greater than 1000. 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 the Java program to find the maximum element in a two-dimensional array:
```java
public class MaxElementIn2DArray {
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}, {121, 122, 123, 124,... | 14,500 |
Implement a Java program that simulates a memory management system. The program should allocate and deallocate memory using a custom memory allocation algorithm. The memory should be divided into fixed-size blocks, and the allocation algorithm should ensure efficient memory usage by considering factors such as fragment... | Here's an example of a Java program that simulates a memory management system using a custom memory allocation algorithm:
```java
import java.util.*;
class MemoryBlock {
private int id;
private boolean allocated;
public MemoryBlock(int id) {
this.id = id;
this.allocated = false;
}
... | 14,603 |
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 is an implementation of the Queue class in Java using a circular linked list:
```java
public class Queue<T> {
private Node<T> front;
private Node<T> rear;
private int capacity;
private int size;
// Node class
private static class Node<T> {
private T data;
private Node<T> n... | 14,659 |
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 is a possible implementation of the given requirements:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Account {
private int accountNumber;
private double balance;
public Account(int accountNumber... | 14,766 |
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. The program should also handle duplicate elements in... | Here is a Java program that finds the kth largest element in an unsorted array and returns its index. It also handles duplicate elements and returns the indices of all occurrences of the kth largest element. The time complexity of the program is O(nlogk).
```java
import java.util.*;
public class KthLargestElement {
... | 14,776 |
Create a new Java program that prints out all the prime numbers between 2 and 1 million, 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 progr... | Here's an example implementation of the requested Java program:
```java
public class PrimeNumberGenerator {
private static final int CHUNK_SIZE = 1000;
public static void main(String[] args) {
int limit = 10000000; // maximum number to check
long startTime = System.currentTimeMill... | 14,985 |
Generate a Java program to read two numbers from the user and print their product. Additionally, the program should handle any potential exceptions that may occur during the user input process. The program should also include input validation to ensure that the user can only enter positive integers. | Here's a Java program that reads two numbers from the user, multiplies them, and handles exceptions and input validation:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
public class ProductCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(Syste... | 15,163 |
Generate a program in Java that reads two strings and checks if the strings are equal. The program should also check if the strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. In addition, the program should count the number of occurrences of e... | Here's a program in Java that meets all the given requirements:
```java
import java.util.Arrays;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "Silent";
boolean isEqual = checkIfStringsAreEqual(str1, str2);
Sys... | 15,182 |
Write a Java program that takes a string as input and returns the number of unique characters in the string.
- The program should use a method called "countUniqueCharacters" to count the unique characters.
- The program should only use a single line of code inside the "main" method to call the "countUniqueCharacters" ... | Here is a Java program that meets all the requirements mentioned:
```java
import java.util.HashSet;
import java.util.Set;
public class UniqueCharacterCounter {
public static int countUniqueCharacters(String input) {
// Remove leading and trailing spaces
input = input.trim();
// Re... | 15,237 |
Write a program that takes two strings as input and appends them together. Your program should follow these steps:
1. Prompt the user to enter the first string.
2. Read and store the first string.
3. Prompt the user to enter the second string.
4. Read and store the second string.
5. Create a new string variable and in... | Here's an example of a program that implements the steps mentioned above in Java:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StringAppendProgram {
public static void main(String[] args) {
try {
BufferedReader reader = new B... | 15,262 |
Write a Java program that takes user input and determines their rating out of 10 based on the following criteria:
1. The user's age: If the user is below 18 years old, their rating is reduced by 2 points. If the user is above 65 years old, their rating is reduced by 1 point.
2. The user's nationality: If the user is fr... | Here is the Java program that takes user input and determines their rating based on the given criteria:
```java
import java.util.Scanner;
public class RatingCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get user input for age
System.out... | 15,488 |
Create a Java method that takes an array of integers as an argument and returns the product of all the integers in the array. The method should have a time complexity of O(n), where n is the length of the array. However, you are not allowed to use any multiplication or division operators in your solution. Additionally,... | Here's a Java method that meets all the given requirements:
```java
public static int getProduct(int[] nums) {
int countNegative = 0;
boolean hasZero = false;
for (int num : nums) {
if (num == 0) {
return 0;
}
if (num < 0) {
countNegative++;
}
... | 15,489 |
Write a Java program to implement Matrix multiplication using only bitwise operators and without using any arithmetic operators. The program should also handle matrices of different sizes efficiently. The time complexity of the program should be O(n^3), where n is the size of the matrices.
Furthermore, the program sho... | Here is an example implementation of a Java program that meets the requirements mentioned:
```java
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] A = {{1, 2}, {3, 4}};
int[][] B = {{5, 6}, {7, 8}};
int[][] result = multiplyMatrix(A, B);
... | 15,601 |
Write a Java program to count the number of unique characters in a sentence without using a loop. Additionally, you should not use any built-in Java methods for counting characters or manipulating strings. The sentence will only consist of lowercase and uppercase letters, spaces, and punctuation marks. The program shou... | Here's a Java program that counts the number of unique characters in a sentence without using a loop and any built-in Java methods for counting characters or manipulating strings:
```java
public class UniqueCharacterCount {
public static void main(String[] args) {
String sentence = "Hello, world!";
... | 15,605 |
Write a Java program that prints all prime numbers between 30 and 1000 (inclusive), using a multi-threaded approach to improve performance. Additionally, the program should implement the Sieve of Eratosthenes algorithm to efficiently generate the prime numbers. | Here's a Java program that prints all prime numbers between 30 and 1000 (inclusive) using a multi-threaded approach and the Sieve of Eratosthenes algorithm:
```java
import java.util.ArrayList;
import java.util.List;
class PrimeGenerator implements Runnable {
private final int start;
private final int end;
... | 15,846 |
Write a Java method to calculate the weighted average marks of a student given their marks of N subjects and their respective credit hours. Each subject has a different credit hour weightage. The number of subjects and their respective marks and credit hours will be provided as input.
The method signature is:
public d... | Here is the corrected code:
```java
public double calculateWeightedAverage(int[] marks, int[] creditHours) {
double weightedSum = 0;
double totalCreditHours = 0;
for (int i = 0; i < marks.length; i++) {
weightedSum += marks[i] * creditHours[i];
totalCreditHours += creditHours[i];
}
... | 15,865 |
Write a program in Java that prints the first 1000 prime numbers and their corresponding Fibonacci numbers. | Here is a program in Java that prints the first 1000 prime numbers and their corresponding Fibonacci numbers:
```java
public class PrimeAndFibonacci {
public static void main(String[] args) {
int count = 0;
int number = 2;
while (count < 1000) {
if (isPrime(number)) {
... | 16,021 |
Write a Java program to generate the following patterns using nested for loops.
Pattern 1:
*
***
*****
*******
*********
*********
*******
*****
***
*
Pattern 2:
*********
*********
*******
*****
***
*
*
***
*****
*******
*********
Pattern 3:
*
***
*****
*******
****... | Here is a Java program to generate the patterns:
```java
public class PatternGenerator {
public static void main(String[] args) {
int rows = 9;
// Pattern 1
System.out.println("Pattern 1:");
for (int i = 1; i <= rows / 2 + 1; i++) {
for (int j = 1; j <= rows - i; j++) {... | 16,050 |
Write a Java program to print out the lyrics of the song "Mary Had a Little Lamb", ensuring that each line of the lyrics is reversed before being printed out. Additionally, the program should capitalize the first letter of each word in the reversed line. However, the program should also handle the case where the lyrics... | Here is a Java program that fulfills the requirements:
```java
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReversedLyrics {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println... | 16,069 |
Construct a Java method to convert a string to its equivalent title case format. The string should contain a maximum of 100 characters and may include special characters. Additionally, the method should ignore the following words when converting to title case: "the", "a", "an".
Title case format means that the first ... | The erroneous code provided incorrectly converts the ignored words ("the", "a", "an") to uppercase, instead of keeping them in lowercase. To fix this, we need to modify the code logic to correctly handle the ignored words.
Here's the corrected implementation of the `convertToTitleCase` method:
```java
public String c... | 16,152 |
Create a boolean variable in Java, initialized to false. Implement a method called `toggleBoolean` that takes in the boolean variable as a parameter and toggles its value. The method should have a time complexity of O(1) and should not use any additional space. Additionally, the implementation should handle concurrent ... | Here's an example implementation that meets all the requirements using Java's `AtomicBoolean`, `Lock`, and `Condition`:
```java
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.co... | 16,317 |
Write a Java method to find and return the k-th largest element in a given array of integers, where k is a positive integer less than or equal to the length of the array. The array will not be empty and will contain at least two distinct elements. The method should have a time complexity of O(n), where n is the length ... | Here's an implementation of the method:
```java
public static int findKthLargest(int[] arr, int k) {
// Convert k to its equivalent index
int index = arr.length - k;
// Call the helper method to find the kth largest element
return findKthLargestHelper(arr, 0, arr.length - 1, index);
}
private sta... | 16,351 |
Create a class in Java that comprises of a date, a location, and temperature reading associated with that location on that particular date. Implement a method within the class that calculates the average temperature for a specific month and year given a list of temperature readings. However, you are now required to opt... | Here's an example implementation that addresses the given requirements using a hashmap to store temperature readings based on their date and a separate hashmap to keep track of the total sum and count of readings for a specific month and year.
```java
import java.util.*;
class TemperatureReading {
private int yea... | 16,437 |
Create a Java program that prints out a word 5 times, but each time it should print the word in a different language. The languages should be randomly selected from a list of at least 10 languages, and the program should ensure that no language is repeated until all the languages have been used. Additionally, the progr... | Here's a corrected version of the Java program that prints out a word 5 times in different languages, ensuring that no language is repeated until all the languages have been used. It also tracks the number of times each language has been used and prints out the language that has been used the least number of times befo... | 16,470 |
Write a Java program to convert a hexadecimal string to an int, without using any built-in Java methods or libraries for hex to int conversion. | Here's a Java program that converts a hexadecimal string to an integer without using any built-in Java methods or libraries for hex to int conversion:
```java
public class HexToIntConverter {
public static void main(String[] args) {
String hexString = "1A"; // Replace with your hexadecimal string
... | 16,487 |
Write code in Java to find the maximum value of the array, while also ensuring that the maximum value is a prime number greater than or equal to 100. Additionally, you must handle cases where the array contains negative numbers and return a meaningful error message if the array is empty. The array can contain up to 10^... | Here's the code in Java that meets the requirements:
```java
import java.util.Arrays;
public class MaxPrimeValue {
public static void main(String[] args) {
int[] array = {1, 3, 2, 5, 6, -4, 7, 8, 101, 103, -200, 105, 97};
int maxPrime = findMaxPrime(array);
System.out.println("Maximum prim... | 16,584 |
Write a piece of code in Java to check if the following string contains at least three numeric characters, one uppercase letter, one lowercase letter, and one special character, with a minimum length of 12 characters. Additionally, ensure that the string does not contain any repeated characters.
#Erroneous Code#
Here ... | Here is a corrected and optimized version of the code:
```java
import java.util.HashSet;
import java.util.Set;
public class PasswordValidator {
public static void main(String[] args) {
String str = "Hello123%World!";
boolean isValid = isValidPassword(str);
System.out.println(isValid);
... | 16,595 |
Create a Java program that reads in a sentence from the user and prints out the lengths of each word in the sentence, excluding any punctuation marks and ignoring any words that contain vowels. The program should also count and display the number of words in the sentence that have an odd length.
Example input: "Hello... | Here's the Java program that reads in a sentence from the user, prints out the lengths of each word in the sentence (excluding punctuation marks and words with vowels), and counts and displays the number of words in the sentence that have an odd length:
```java
import java.util.Scanner;
public class WordLengths {
... | 16,648 |
Write a Java program to convert a given integer value to its Roman numeral representation, while also ensuring that the input value is within the range of -5000 to 5000. The program should handle the conversion for decimal numbers up to two decimal places, and should include error handling for invalid inputs. | Here's a Java program that converts an integer value to its Roman numeral representation, while also ensuring the input value is within the range of -5000 to 5000. The program also handles decimal numbers up to two decimal places and includes error handling for invalid inputs.
```java
import java.text.DecimalFormat;
i... | 16,680 |
Write a Java web service that takes in an input string and returns the string "Hello world" if the input is a palindrome. The web service should handle multiple concurrent requests and should be able to handle large input strings efficiently.
In addition to the given requirements, the web service should validate the i... | Here's an example implementation of a Java web service that meets the given requirements:
```java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicI... | 16,737 |
Write a Java program to perform a binary search on a sorted array of integers to find a given number. The array may contain duplicate elements. The program should return the index of the first occurrence of the number if found, and -1 if not found.
Additionally, the program should handle cases where the array is not s... | Here's a Java program that performs a binary search on a sorted array of integers to find a given number. It returns the index of the first occurrence of the number if found, and -1 if not found. It also handles cases where the array is not sorted in ascending order and returns -1 in those cases.
```java
public class ... | 16,784 |
Create a thread-safe singleton class with lazy initialization and ensure that the singleton instance is immutable. Additionally, the singleton class should be able to handle concurrent requests efficiently by implementing a lock-free mechanism such as using atomic operations or non-blocking synchronization. | Here is an example of a thread-safe singleton class with lazy initialization, immutable instance, and a lock-free mechanism using atomic operations:
```java
import java.util.concurrent.atomic.AtomicReference;
public class Singleton {
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<>... | 16,856 |
Write a Java method to convert a given decimal number to its equivalent English words. However, you must implement the conversion logic yourself without using any pre-built libraries or classes for number to word conversions. You can only use basic arithmetic and string manipulation operations to achieve the desired re... | Here's a Java method that can convert a given decimal number to its equivalent English words:
```java
public class NumberToWordsConverter {
private static final String[] UNITS = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
private static final String[] TEENS = {"ten", "eleven"... | 16,865 |
Create a Java program for solving cubic equations with complex roots. The program should handle both real and complex coefficients. Additionally, implement a user interface that allows the user to input the coefficients and displays the roots of the equation. | Here is a Java program that solves cubic equations with complex roots and includes a user interface:
```java
import java.util.Scanner;
public class CubicEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Cubic Equation Solver")... | 16,929 |
Create an algorithm in Java to print all the prime numbers between a given range, while minimizing the time complexity as much as possible. Additionally, the algorithm should optimize space complexity by using a memory-efficient data structure. The algorithm should also handle a large range of numbers efficiently, spec... | To print all prime numbers between a given range while minimizing time and space complexity, we can use the Sieve of Eratosthenes algorithm. This algorithm works by iteratively marking the multiples of each prime, starting from 2, as composite. The remaining numbers are prime.
Here's an implementation of the algorithm... | 16,952 |
Generate a 2D array with a variable number of rows and columns in Java. Initialize each element of the array with a random integer between -100 and 100. Each row of the array should have at least one element greater than or equal to 90. Implement a method that takes the generated array as input and returns the sum of a... | Here is a Java code snippet that generates a 2D array with a variable number of rows and columns, initializes each element with a random integer between -100 and 100, and ensures that each row has at least one element greater than or equal to 90. It also implements a method that takes the generated array as input and r... | 16,988 |
Create an array of strings in Java with 100 elements, where each element is a randomly generated string consisting of uppercase letters only. Additionally, each string should have a length of exactly 10 characters. The randomly generated strings should not contain any repeated characters. | Here's a Java code that generates an array of 100 strings, where each string consists of randomly generated uppercase letters without any repeated characters:
```java
import java.util.*;
public class RandomStringArray {
public static void main(String[] args) {
String[] randomStrings = new String[100];
... | 17,084 |
Write a Java program to find the element that appears maximum number of times in an array. If multiple elements have the same maximum frequency, return the one with the highest value. The time complexity of the solution should be O(n), where n is the size of the array.
int [] arr1 = {2, 8, 7, 2, 8, 2, 6, 7, 8, 7} | Here is a Java program that finds the element that appears maximum number of times in an array and returns the one with the highest value if multiple elements have the same maximum frequency:
```java
import java.util.HashMap;
import java.util.Map;
public class MaxFrequencyElement {
public static int findMaxFreque... | 17,229 |
Create a Java program to count and print the distinct prime numbers in an array while ignoring any duplicates, and sort the distinct prime numbers in descending order. The array should be of size greater than or equal to 100, and the elements should be non-negative integers. The time complexity of your solution should ... | Here is a Java program that counts and prints the distinct prime numbers in an array, ignores duplicates, and sorts the distinct prime numbers in descending order:
```java
import java.util.*;
public class PrimeNumbers {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1, 4, 3, 2, 5, 7, 6... | 17,290 |
Generate a Java code snippet for declaring an empty list with a specific data type, limiting the maximum number of elements to 1000, ensuring that the list is sorted in ascending order, and adding a custom sorting criteria based on a property of the elements. | Sure! Here's a Java code snippet that fulfills all the requirements:
```java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<MyClass> myList = new ArrayList<>();
myList.sort(Comparator.comparing(MyCla... | 17,292 |
Create a method in Java that takes an integer as input and returns a boolean value indicating whether the number is a prime number or not. Additionally, the method should also handle and return false for any negative input values, zero, and one.
To increase the difficulty, add a requirement that the method should be i... | Here's a recursive implementation of a method that checks if a number is prime or not in Java:
```java
public class PrimeNumberChecker {
public static boolean isPrime(int number) {
// Check if number is negative, zero, or one
if (number < 2) {
return false;
}
// Call the... | 17,300 |
Write a Java program that takes a number as input and prints the factorial of that number. The program should include error handling for invalid inputs and should use recursion to calculate the factorial.
The program should also display the intermediate steps of the factorial calculation. For example, if the input num... | Here is the Java program that takes a number as input and prints the factorial of that number using recursion:
```java
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ")... | 17,324 |
Generate a Java program that takes two strings as input and compares them for equality. The program should consider the following conditions:
1. Case Sensitivity: The program should compare the strings while considering the case sensitivity. For example, "Hello" and "hello" should be considered different.
2. Leading/... | Here is an example Java program that meets the given requirements:
```java
import java.text.Normalizer;
public class StringComparator {
public static void main(String[] args) {
String str1 = " Héllö! ";
String str2 = "hello";
boolean equal = compareStrings(str1, str2);
Sy... | 17,350 |
Create a random number generator in Java that produces a random integer between 1 and 1000, but only multiples of 5. Additionally, ensure that the generated numbers are in descending order. | Here is a Java code snippet that generates random multiples of 5 between 1 and 1000 in descending order:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
ArrayList<Integer> multiplesOfFi... | 17,405 |
Create a Java class that prints "Welcome to my program" when initialized, but only if the current date is a prime number, the hour is a prime number, and the program is being run on a leap year. | Here is a Java class that prints "Welcome to my program" when initialized, but only if the current date is a prime number, the hour is a prime number, and the program is being run on a leap year.
```java
import java.time.LocalDateTime;
public class PrimeLeapYearProgram {
public PrimeLeapYearProgram() {
... | 17,479 |
Create a Java program that prompts the user to enter a positive integer n and calculates the sum of the first n prime numbers. The program should handle input validation and error handling for non-integer inputs and negative values of n.
Note: A prime number is a whole number greater than 1 that is divisible by only 1... | Here is a Java program that prompts the user to enter a positive integer n and calculates the sum of the first n prime numbers:
```java
import java.util.Scanner;
public class SumOfFirstNPrimes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 0;
bo... | 17,678 |
Construct an array of size 20 to store integers in Java. Initialize the array with random numbers between -1000 and 1000. Calculate the sum of all the prime numbers in the array and display the result. Additionally, display the maximum and minimum prime numbers found in the array. | Here's the Java code to implement your requirements:
```java
import java.util.Random;
public class PrimeNumberArray {
public static void main(String[] args) {
int[] array = new int[20];
Random random = new Random();
// Initialize the array with random numbers between -1000 and 1000
... | 17,797 |
Write a Java code snippet to create an array of integers of length N, where N is a user input. The array should only contain prime numbers and each element should be unique.
#Erroneous Code#
```java
import java.util.Scanner;
public class PrimeArray {
public static void main(String[] args) {
Scanner input ... | To fix this error, we need to update the getNextPrime() method. Below is the corrected code:
```java
import java.util.Arrays;
import java.util.Scanner;
public class PrimeArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of t... | 17,813 |
Write a Java method that takes an array of integers as input and returns the maximum sum that can be obtained by selecting a contiguous subarray from the input array. The method should have a time complexity of O(n), where n is the length of the input array.
Additionally, the method should throw an IllegalArgumentExce... | Here is an example of a Java method that finds the maximum sum of a contiguous subarray in an array of integers:
```java
public static int findMaxSubarraySum(int[] nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("Input array is empty");
}
if (containsOnlyNegative(nums)) {
... | 17,824 |
Create a Java program to read in a number n (1 ≤ n ≤ 100), and print out the first n lines of Pascal's triangle.
Additional requirements:
1. The program should be able to handle extremely large values of n efficiently, without causing a stack overflow or excessive memory usage.
2. The program should use a recursive ap... | Here is a Java program that meets the given requirements:
```java
import java.math.BigInteger;
public class PascalTriangle {
private static final int MAX_RECURSION_DEPTH = 1000;
public static void main(String[] args) {
int n = 10; // Change this to the desired value of n
printPascalsTriangle(... | 17,829 |
Write a program in Java that takes a two-dimensional array of integers as input and calculates the sum of all its elements using a nested for loop. The program should also track and print the average of all the elements in the array. Additionally, the program should find and print the minimum and maximum values in the ... | Here is an example of a program that fulfills the requirements:
```java
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
int[][] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int sum = 0;
int count = 0;
int min = Integer... | 17,866 |
Create a Java program that finds the first 100 prime numbers and stores them in an array. The program should use a custom method to check if a number is prime. The method should be implemented using a more efficient algorithm than simply checking all divisors up to the square root of the number. The program should also... | Here's an example Java program that finds the first 100 prime numbers using multi-threading:
```java
import java.util.ArrayList;
import java.util.List;
public class PrimeNumberGenerator {
public static void main(String[] args) {
int n = 100; // Number of prime numbers to generate
List<Integer> p... | 17,906 |
Write a Java method to remove repeated elements from an array of integers, while maintaining the original order of the elements.
Additional requirements:
1. The time complexity of the method should be O(n), where n is the length of the array.
2. The space complexity of the method should be O(1), i.e., no additional sp... | Here's a possible implementation of the method:
```java
public static int removeDuplicates(int[] arr) {
int n = arr.length;
if (n == 0 || n == 1) {
return n;
}
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i + 1]) {
arr[j++] = arr[i];
}
... | 17,931 |
Write a Java method to return the kth largest element from an array of integers, where k is provided as an input parameter. The array may contain duplicate elements.
The kth largest element is the element that would appear in the kth position if the array were sorted in non-decreasing order.
For example, given the ar... | Here's a possible implementation in Java:
```java
import java.util.PriorityQueue;
public class KthLargestElement {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
... | 17,969 |
Create a switch statement to display the corresponding number in words. The number should be between 1 and 1000 (inclusive). Additionally, implement error handling to display an appropriate message if the number is outside this range. However, for numbers divisible by 7, instead of displaying the number in words, displ... | Here's an example of how you can create a switch statement to display numbers in words, with the additional conditions for "Fizz", "Buzz", and "FizzBuzz":
```java
public class NumberToWordConverter {
public static void main(String[] args) {
int number = 105; // Replace with the desired number
... | 17,979 |
Create a data structure in Java to store books and their associated information like ISBN, authors, publication date, and number of pages. Implement the following operations:
1. Add a new book to the collection. (Time complexity: O(1), Space complexity: O(1))
2. Remove a book from the collection. (Time complexity: O(1... | Here is the implementation of the data structure in Java:
```java
import java.util.*;
public class BookCollection {
private Map<String, Book> booksByISBN;
private List<Book> booksByPublicationDate;
public BookCollection() {
booksByISBN = new HashMap<>();
booksByPublicationDate = new Array... | 18,150 |
Create a Java class to find all distinct substrings of a given string. The substring should not contain any repeating characters.
The program should take a string as input and print all the distinct substrings without any repeating characters. The program should have a time complexity of O(n^2) and a space complexity ... | Here is the Java code to find all distinct substrings of a given string:
```java
import java.util.HashSet;
public class DistinctSubstrings {
public static void findDistinctSubstrings(String str) {
HashSet<String> set = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
Str... | 18,163 |
Create a Java class called 'Rectangle' that has the following properties and methods:
Properties:
- length (integer)
- width (integer)
Methods:
1. `calculateArea()`: This method should return the area of the rectangle.
2. `calculatePerimeter()`: This method should return the perimeter of the rectangle.
3. `isSquare()... | Here is the corrected code for the `Rectangle` class with the `resize(int factor)` method implemented correctly:
```java
public class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
if (length < 1 || length > 100 || width < 1 || width > 100) {
... | 18,205 |
Construct a nested for loop in Java using the following parameters: Initial value of i set to zero, condition as i is greater than or equal to -10, and iteration of i as multiplication by three. The outer loop should iterate from 1 to 10, and the inner loop should iterate from 1 to the current value of the outer loop c... | Here is the nested for loop in Java with the given parameters:
```java
for (int i = 0; i >= -10; i *= 3) {
for (int j = 1; j <= i; j++) {
System.out.println(i + " " + j);
}
}
```
And here is the erroneous code that attempts to increment `i` within the inner loop body:
```java
for (int i = 0; i >= -10... | 18,370 |
Write a Java method to swap the values of two integer variables without using a temporary variable. Additionally, handle the case where the input integers are equal and provide an error message for this scenario. Furthermore, the swapping operation should be done in constant time complexity. | Here's a Java method that swaps the values of two integer variables without using a temporary variable, handles the case where the input integers are equal, and performs the swapping operation in constant time complexity:
```java
public static void swapIntegers(int a, int b) {
if (a == b) {
System.out.prin... | 18,421 |
Create a class in Java which computes the sum of the cube of all prime numbers between k and n, where k and n are positive integers. The program should be able to handle large values of k and n efficiently.
Additional Requirements:
1. Implement the class using a custom data structure for efficient prime number generat... | Here is a class that implements the requirements stated above:
```java
import java.util.*;
class PrimeNumberGenerator {
private boolean[] sieve;
private List<Integer> primes;
public PrimeNumberGenerator(int n) {
sieve = new boolean[n + 1];
primes = new ArrayList<>();
generatePrim... | 18,457 |
Create a program using Java to print the sum of the first 100 prime numbers.
To solve this problem, you will need to do the following steps:
1. Define a method to check if a given number is prime.
2. Initialize a counter variable to keep track of the number of prime numbers found.
3. Initialize a variable to store th... | Here is the code for the program:
```java
public class SumOfPrimes {
public static void main(String[] args) {
int counter = 0;
int sum = 0;
int number = 2;
while (counter < 100) {
if (isPrime(number)) {
counter++;
sum += number;
... | 18,489 |
Create a class in Java that performs the following task: print out all characters of a given string along with their position in the string, but only for vowels. Additionally, count and print the number of vowels in the string, display the vowels in uppercase, and remove any duplicate vowels before printing. | Here is an example of a class in Java that performs the task described:
```java
public class VowelPrinter {
public static void main(String[] args) {
String inputString = "Hello, World!";
printVowels(inputString);
}
public static void printVowels(String inputString) {
String vowels... | 18,587 |
Write a Java code to encrypt a password using `bcrypt` hash algorithm with a cost factor of 15 and also add a salt to further increase the security.
String password = "password123";
Hint: The `bcrypt` algorithm is considered to be more secure than `sha256` and allows for a cost factor and salt to be specified for the... | To encrypt a password using the bcrypt hash algorithm with a cost factor of 15 and a salt, you can use the `BCrypt` class provided by the `jBCrypt` library. You can add the `jBCrypt` library to your project by including the corresponding JAR file.
Here's an example code snippet that demonstrates how to encrypt a passw... | 18,659 |
Write a Java program to categorize each of the following strings and numbers as a palindrome or not, while also considering additional constraints.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization.
Yo... | Here's the Java program that implements the requirements mentioned:
```java
import java.util.Arrays;
public class PalindromeChecker {
public static void main(String[] args) {
Object[] objects = { "madam", "DAD", "superman", "abcdef", 12321, 12345 };
for (Object obj : objects) {
System... | 18,662 |
Write a Java program that calculates the sum of all prime numbers from 1 to 1000 and prints the result. | Here is a Java program that calculates the sum of all prime numbers from 1 to 1000 and prints the result:
```java
public class SumOfPrimes {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; i++) {
if (isPrime(i)) {
sum += i;
}
... | 18,686 |
Create an object-oriented programming class in Java named "Car" with four private instance variables "make", "speed", "color", and "maxSpeed". The "make" variable should only accept one of the following values: "Toyota", "Honda", or "Ford". The "speed" variable should only accept positive integer values greater than or... | Here is the implementation of the "Car" class in Java:
```java
public class Car {
private String make;
private int speed;
private String color;
private int maxSpeed;
public Car(String make, int speed, String color) {
setMake(make);
setSpeed(speed);
setColor(color);
... | 18,706 |
Create a program in Java that takes an array with two positive prime numbers as input and prints the result of raising the first number to the power of the second number. The program should handle cases where the input array does not contain two positive prime numbers and display an error message in such cases.
Additi... | Here's an example program that meets the requirements:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class PrimePowerCalculator extends JFrame {
private JTextField firstNumberFiel... | 18,727 |
Create a method named 'combine' to combine two strings, where the length of each string is at most 100 characters. String str1 = "Hello"; String str2 = "World"; Ensure that the combined string does not exceed a length of 150 characters. Additionally, the combined string should not contain any vowels. | Here's the code for the 'combine' method that meets the given requirements:
```java
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String combined = combine(str1, str2);
System.out.println(combined);
}
public s... | 18,762 |
Write a program in a programming language of your choice that demonstrates the concept of static variables in a multi-threaded environment. The program should have a class with a static variable and two methods. The first method should increment the static variable by 1, and the second method should print the value of ... | Here's an example program in Java that demonstrates the concept of static variables in a multi-threaded environment, with proper synchronization to prevent race conditions:
```java
public class StaticVariableDemo {
private static int staticVariable = 0;
public static void incrementStaticVariable() {
s... | 18,777 |
Create a series of nested for loops in Java to print the prime numbers between 1 and 1000 in descending order on separate lines. Additionally, modify the code to skip printing any prime numbers that end with the digit 5. Furthermore, implement a condition to only print the prime numbers that are also palindromic number... | Here is the code that meets your requirements:
```java
public class PrimeNumberPrinter {
public static void main(String[] args) {
for (int i = 1000; i >= 1; i--) {
if (isPrime(i) && !endsWithFive(i) && isPalindromic(i)) {
System.out.println(i);
}
}
}
... | 18,791 |
Construct a method in Java that takes in an integer as input and returns true if the integer is a prime number, and false otherwise. The method should have a time complexity of O(log(n)^2). | Here's a Java method that checks if an integer is prime and has a time complexity of O(log(n)^2):
```java
public static boolean isPrime(int n) {
// Check if the number is less than 2
if (n < 2) {
return false;
}
// Check if the number is divisible by any number from 2 to the square root of... | 18,863 |
Write a code in Java that will get all the prime numbers from an array of integers and store them in a separate array. Additionally, the code should display the sum of all the prime numbers found. The code should have a time complexity of O(n^2) or better, where n is the length of the input array. | Here is a Java code that finds and stores all the prime numbers from an array of integers in a separate array, and also displays their sum:
```java
public class PrimeNumbers {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt... | 18,879 |
Create a program that takes two inputs, an array of strings and an array of integers. Output an array with the strings at the same indices as the integers. The integers in the second array represent the indices of the strings in the first array that need to be rearranged.
String[] strings = {"cat", "dog", "bird", "fis... | Here's an updated solution that meets all the new requirements:
```java
public class StringRearranger {
public static void main(String[] args) {
String[] strings = {"cat", "dog", "bird", "fish"};
int[] indices = {1, 0, 3, 2};
String[] rearrangedStrings = rearrangeStrings(strings, i... | 18,900 |
Write a method in Java to return a reversed version of a given string, but only reverse the alphabetical characters in the string while keeping the non-alphabetical characters in their original positions. Additionally, make sure the method is case-insensitive, meaning that the reversal should work for both uppercase an... | Here's the implementation of the method in Java:
```java
public class ReverseAlphabeticalCharacters {
public static String reverseAlphabetical(String input) {
char[] characters = input.toCharArray();
int left = 0;
int right = input.length() - 1;
while (left < right) {
... | 19,166 |
Create a Java program that prints out the contents of a given two-dimensional array in a spiral pattern. The array will have dimensions M x N, where M represents the number of rows and N represents the number of columns. The program should print the elements of the array in a clockwise spiral pattern, starting from the... | Here's a Java program that prints out the contents of a given two-dimensional array in a spiral pattern:
```java
public class SpiralPrint {
public static void spiralPrint(int[][] arr) {
int topRow = 0;
int bottomRow = arr.length - 1;
int leftColumn = 0;
int rightColumn = arr[0].leng... | 19,220 |
Create a multithreaded program that finds all the prime numbers less than or equal to a given number. The program should use a minimum of two threads to divide the workload and ensure efficient execution. Additionally, implement a user interface that allows the user to input the number and view the generated prime numb... | Sure! Here's a multithreaded program in Java that finds all the prime numbers less than or equal to a given number:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrimeNumberFinder {
private static List<Integer> primeNumbers;
public static void main(String[... | 19,282 |
Write a Java program to generate a random number between 1 and 100, inclusive, and determine if it is prime. | Here's a Java program that generates a random number between 1 and 100 (inclusive) and determines if it is prime:
```java
import java.util.Random;
public class PrimeNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
... | 19,301 |
Create a Java program which takes an integer array as a parameter, sorts the array in descending order using a merge sort algorithm, and returns the sorted array.
Additional Requirements:
- The time complexity of the sorting algorithm should be O(n log n).
- The space complexity should be O(n). | Here's an implementation of the Java program that sorts an integer array in descending order using the merge sort algorithm:
```java
public class MergeSortDescending {
public static void main(String[] args) {
int[] arr = {9, 3, 7, 1, 5};
int[] sortedArr = mergeSortDescending(arr);
... | 19,329 |
Create a method in Java to return the largest prime number less than a given number. The method should have a time complexity of O(sqrt(n)), where n is the given number. | Here is a Java method that returns the largest prime number less than a given number, with a time complexity of O(sqrt(n)):
```java
public class LargestPrimeNumber {
public static int getLargestPrime(int number) {
// Check if the number is less than 2
if (number < 2) {
throw new Illega... | 19,529 |
Write code in Java to create a circular doubly linked list with the following requirements:
1. Each node in the list should contain an integer value and a reference to the previous and next nodes.
2. The list should have a method to add a new node at the beginning.
3. The list should have a method to add a new node at ... | Here is the Java code to create a circular doubly linked list with the given requirements:
```java
public class CircularDoublyLinkedList {
private Node head;
private class Node {
private int value;
private Node previous;
private Node next;
public Node(int valu... | 19,584 |
Implement a Java program for finding the index of the first occurrence of a target element in a sorted array. The array can contain duplicates.
Requirements:
- The time complexity of your solution should be O(log n), where n is the size of the array.
- The space complexity of your solution should be O(1), i.e., it sho... | Here's the implementation of the Java program that finds the index of the first occurrence of a target element in a sorted array, even if the array contains duplicates.
```java
public class Main {
public static int findFirstOccurrence(int[] arr, int target) {
int left = 0;
int right = arr.length - ... | 19,618 |
Create a for loop in Java that iterates over the given array and prints only the even values in ascending order.
Array: int[] arr = {1, 2, 3, 4, 5}; | Here is the for loop in Java that iterates over the given array and prints only the even values in ascending order:
```java
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
System.out.println(arr[i]);
}
}
```
Output:
```
2
4
``` | 19,657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.