instruction stringlengths 38 3.13k | output stringlengths 288 7.87k | __index_level_0__ int64 34 58.2k |
|---|---|---|
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 is an example of a Java program that prints the contents of a given two-dimensional array in a spiral pattern:
```java
public class SpiralArrayPrinter {
public static void printSpiralArray(int[][] arr) {
int m = arr.length;
int n = arr[0].length;
int topRow = 0, bottomRow = m - 1;
... | 34 |
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(1) (constant space).
- You ... | To fix the erroneous code, we need to correct the initialization of the `left` and `right` arrays in the `mergeSort` method. Instead of creating arrays of size `mid`, we need to create `left` and `right` arrays of sizes `mid` and `arr.length - mid`, respectively. This will ensure that all elements of the original array... | 146 |
Create a Java program to take a given string and replace all occurrences of a given letter with another given letter. Additionally, the program should only replace the given letter if it is at the beginning or the end of a word in the string. The program should also count and display the total number of replacements ma... | Here is a Java program that fulfills the given requirements:
```java
import java.util.Scanner;
public class ReplaceLetterInString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the string, letter to replace, and replacement letter
System.out.... | 149 |
Write a Java program to calculate the product of two given integers. The program should take two integers as input from the user and display the product.
Additional Requirements:
1. Validate the input to ensure that the user enters valid integers. If the input is not a valid integer, display an error message and ask t... | Here's an example Java program that calculates the product of two given integers:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1, num2;
// Validate the input for the first integer
w... | 184 |
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 is a Java program that implements the requirements mentioned above:
```java
public class FirstOccurrence {
public static int findFirstOccurrence(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
int result = -1;
while (left <= right) {
int mid = l... | 436 |
Create a for loop in Java that iterates over the given array and prints only the prime numbers in ascending order. Additionally, the loop should terminate once it encounters the first composite number in the array.
Array: int[] arr = {2, 3, 4, 5, 6, 7, 8, 9, 10}; | Here is a for loop in Java that iterates over the given array, prints only the prime numbers in ascending order, and terminates once it encounters the first composite number in the array:
```java
int[] arr = {2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int num : arr) {
boolean isPrime = true;
if (num < 2) {
isPrime ... | 466 |
Create an array in Java with 100,000,000 floating-point values and output the average, median, and mode of these values. Additionally, implement the calculation of the standard deviation of the array. | To create an array in Java with 100,000,000 floating-point values, you can use the following code:
```java
import java.util.Arrays;
public class Statistics {
public static void main(String[] args) {
int size = 100000000;
float[] array = new float[size];
// Fill the array with rand... | 509 |
Write a Java program to find all pairs of distinct integers in an array that sum up to a given target integer. The program should print the indices of these pairs.
The input consists of an array of unique integers and a target integer. The output should be a list of pairs, where each pair is represented by the indices... | Here is one possible implementation of the program:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PairSum {
public static void main(String[] args) {
int[] array = {2, 3, 4, 5, 6, 7, 7, -3, -1, -5};
int target = 9;
L... | 595 |
Write a Java program to find the sum of elements in an n x n matrix, where n is a positive integer. The matrix is represented as a two-dimensional array of integers. The program should take input from the user for the size of the matrix and then prompt the user to enter the elements of the matrix.
The program should t... | Here is a Java program that addresses all the mentioned scenarios:
```java
import java.util.Scanner;
public class MatrixSumRecursive {
private static double[][] matrix;
private static double[][] memo;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Syste... | 636 |
Implement a stack data structure in Java with the following additional requirements:
1. The stack should have a maximum capacity of 1000 elements. If an attempt is made to push an element onto a full stack, it should throw a StackOverflowException.
2. The stack should support an additional operation called "getMinimum... | Here is an implementation of the stack with the additional requirements:
```java
import java.util.Arrays;
public class Stack {
private int[] stack;
private int top;
private int min;
private double median;
public Stack() {
stack = new int[1000];
top = -1;
min = Integer.MAX_... | 665 |
Implement a heap sort algorithm in Java without using any additional data structures or libraries. The algorithm should only use a fixed-size array to perform the sorting. Additionally, the array size should be limited to 100 elements and the implementation should be able to handle duplicate elements in the array effic... | Here is a Java implementation of heap sort algorithm using a fixed-size array of maximum 100 elements. This implementation can handle duplicate elements efficiently.
```java
public class HeapSort {
private static int heapSize;
public static void sort(int[] array) {
buildHeap(array);
... | 673 |
Create a generic array of size N (where N is a positive integer) using Java and sort it using the bubble sort algorithm. Additionally, add a condition to the sorting algorithm that allows for sorting the array in descending order instead of ascending order. The array should contain objects of a custom class that implem... | Here is an example implementation that meets all the requirements mentioned:
```java
import java.util.Comparator;
interface CustomInterface {
// method to be implemented by custom class
void customMethod();
}
class CustomClass implements CustomInterface {
private int value;
public CustomClass(int va... | 678 |
Write a Java Method that takes an array of integers and returns true if the array is sorted in ascending order, does not contain any duplicate values, has a size greater than 5, and all the elements are prime numbers. | Here is a Java method that satisfies the given conditions:
```java
public static boolean isSortedAscendingNoDuplicatesPrime(int[] arr) {
// Check if array size is greater than 5
if (arr.length <= 5) {
return false;
}
// Check if array is sorted in ascending order
for (int i = 0; i < arr.le... | 779 |
Write a method that prints out all the prime numbers between 1 and 1,000,000,000 and also calculates the sum of all these prime numbers. | To find all the prime numbers between 1 and 1,000,000,000, and calculate their sum, we can use the Sieve of Eratosthenes algorithm, which efficiently identifies all prime numbers up to a given limit.
Here's a method in Java that implements this algorithm:
```java
public static void printAndSumPrimes(int limit) {
... | 785 |
Write a Java method that takes a string and prints out the number of occurrences of each unique vowel in the string, while also keeping track of the total count of consonants in the string. Ignore case sensitivity and consider vowels to be the letters 'a', 'e', 'i', 'o', and 'u'. The string may contain special characte... | Here's the Java method that meets the requirements mentioned:
```java
import java.util.HashMap;
import java.util.Map;
public class VowelCount {
public static void main(String[] args) {
String input = "Hello World!";
try {
countVowelsAndConsonants(input);
} catch (InvalidString... | 797 |
Write a Java program that takes an integer as input and checks if it is a prime number. If the input is a prime number, print "The number is prime." If the input is not a prime number, print "The number is not prime." Additionally, handle the case when the input is not a valid integer and print "Invalid input." The pro... | Here is a Java program that takes an integer as input and checks if it is a prime number, while also handling the mentioned edge cases:
```java
import java.util.Scanner;
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.... | 816 |
Implement a custom LinkedList class in Java without using any built-in data structures or collections libraries. The custom LinkedList should have the following methods:
- addFirst(element): adds the specified element to the beginning of the list
- addLast(element): adds the specified element to the end of the list
- r... | Here is an implementation of a custom LinkedList class in Java:
```java
public class LinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
public void addFirst(T element) {
Node<T> newNode = new Node<>(element);
if (head == null) {
head = newNode;
... | 821 |
Implement the following algorithm in Java, with a slight modification to the original bubble sort algorithm.
// Modified Bubble sort algorithm
for i in 1 to n-1
for j in 0 to n-i-1
if array[j] < array[j+1]
swap array[j] and array[j+1]
Your task is to modify the bubble sort algorithm to sort the array ... | Here is the modified bubble sort algorithm implemented in Java to sort an array in descending order:
```java
public class BubbleSortDescending {
public static void bubbleSortDescending(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
... | 910 |
Create a method that prints all elements of an array, but also includes the following conditions:
- Only print elements greater than 2.
- Only print elements that are even numbers.
- Sort the elements in descending order before printing them.
- The array must contain at least 5 elements.
- The array must not contain an... | Here is a possible implementation in Java:
```java
import java.util.Arrays;
public class ArrayPrinter {
public static void printElements(int[] arr) {
// Check if the array contains at least 5 elements
if (arr.length < 5) {
System.out.println("Array must contain at least 5 elements.");
... | 975 |
Write a Java program that prompts the user to enter 5 integers and stores them in an array. The program should then calculate and display the sum, average, maximum, and minimum values of the entered integers. | Here is a Java program that prompts the user to enter 5 integers and calculates the sum, average, maximum, and minimum values of the entered integers:
```java
import java.util.Scanner;
public class IntegerArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
... | 995 |
Write a code in Java to replace all the occurrences of a given value in an array with a new value. If the given value is not found in the array, the code should print an error message "Value not found".
arr = [2, 5, 1, 5, 8]
Additional Requirements:
1. The code should handle both primitive integer arrays and array li... | For the first part of the question, where we need to replace occurrences of a given value in a one-dimensional array, we can use the following code:
```java
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayReplacement {
public static void replaceValue(int[] arr, int oldValue, int newVal... | 1,021 |
Write a Java program that creates a GUI window with a button. When the button is clicked, display a message box with a customized message based on the user's name and the selected option from a drop-down menu. Additionally, implement the following features:
1. Allow the user to enter their name in a text field. The cu... | Here's an example Java program that fulfills all the mentioned requirements:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class CustomizedMessageGUI extends JFrame {
private JLabel nameLabel;
private JTextField nameField;
private JButton button;... | 1,053 |
Generate a for loop in Java to display all prime numbers between 1 and 50, excluding the numbers 7 and 13. | Here is an example of a for loop in Java to display all prime numbers between 1 and 50, excluding the numbers 7 and 13:
```java
public class PrimeNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 50; i++) {
if (i == 7 || i == 13) {
continue; // Skip numbers... | 1,101 |
Implement a recursive Insertion Sort algorithm in Java.
Additional requirement: The implementation must not use any additional data structures (such as arrays, lists, or queues) for sorting.
Reference code:
```
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, ... | Here is the corrected code for the recursive Insertion Sort algorithm in Java:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
insertionSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
p... | 1,139 |
Write a Java program to generate a random number between 1000 and 5000, but ensure that the generated number is divisible by both 7 and 11 and does not contain the digit 5. | Here is a Java program that generates a random number between 1000 and 5000, ensuring that the generated number is divisible by both 7 and 11 and does not contain the digit 5:
```java
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new... | 1,236 |
Implement a thread pool in Java that supports dynamic resizing of the pool based on the current workload. Additionally, the thread pool should have a scheduling mechanism that prioritizes tasks based on their urgency, estimated execution time, and resource requirements, and assigns them to threads accordingly. The sche... | Below is an example of how you can implement a thread pool in Java with dynamic resizing, task scheduling, and error handling mechanisms:
```java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.BlockingQ... | 1,347 |
Write a Java method to check if a numerical value is within a specified range and return the number of times the value appears in the range. The method should have a time complexity of O(n), where n is the length of the input array `nums`.
Signature:
```java
public static int countValuesInRange(int[] nums, int startRa... | To solve this problem within the given time complexity constraint, we can use a simple iterative approach. We will iterate over each element in the array `nums` and count the number of elements that fall within the specified range `[startRange, endRange]`.
Here is the Java code that implements this logic:
```java
pu... | 1,382 |
Create a for loop in Java using the given array and print out the sum of all prime numbers in the array. Additionally, handle any exceptions that may occur while calculating the sum. | Sure, here's an example of a for loop in Java that calculates the sum of all prime numbers in a given array, and handles any exceptions that may occur:
```java
public class PrimeNumberSum {
public static void main(String[] args) {
int[] numbers = { 2, 5, 8, 11, 13, 15, 17, 19 };
int sum = 0;
... | 1,400 |
Write a Java program that calculates the volume of a triangular prism, given the length of the base, the height of the triangle, and the height of the prism.
Erroneous code reference:
```
double baseLength = 6.5;
double triangleHeight = 4.8;
double prismHeight = 9.2;
// Calculate the area of the base triangle
double... | Here is the corrected Java code:
```java
public class TriangularPrismVolumeCalculator {
public static void main(String[] args) {
double baseLength = 6.5;
double triangleHeight = 4.8;
double prismHeight = 9.2;
// Calculate the area of the base triangle
double baseArea = (ba... | 1,569 |
Create a Java program that reads an array of integers from the console and prints out the largest number. The program should also check if the input array contains any negative numbers and display an error message if it does. Additionally, the program should ensure that the array contains at least 5 integers and that t... | Here is a Java program that meets the given requirements:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[5];
try {
... | 1,577 |
Create an algorithm in Java to sort an array in descending order using the "QuickSort" sorting algorithm.
However, there are two bugs in the provided code that need to be fixed before the array can be correctly sorted. Find and correct the bugs in the code.
array = [10, 15, 7, 2, 13, 18]
Note: The bugs may be relate... | Here is the corrected code to sort an array in descending order using the QuickSort algorithm:
```java
public class QuickSortDescending {
public static void main(String[] args) {
int[] array = {10, 15, 7, 2, 13, 18};
quickSortDescending(array, 0, array.length - 1);
// Prin... | 1,594 |
Write a Java program to find the second maximum and second minimum values in an array of integers, excluding any duplicates. The program should handle cases where all elements in the array are duplicates by only considering one instance of each duplicate value. If the array is empty or contains only one element, the pr... | Here is the Java program to find the second maximum and second minimum values in an array of integers, excluding any duplicates:
```java
import java.util.Arrays;
public class SecondMinMax {
public static void findSecondMinMax(int[] arr) {
int n = arr.length;
if (n < 2) {
... | 1,681 |
Create a Java program to convert a 2D array of positive integers into a single positive integer. The 2D array represents a matrix, where each element in the array represents a digit. The resulting integer should be obtained by reading the digits row by row, from left to right. The input array is guaranteed to have at l... | Here is the Java program that converts a 2D array of positive integers into a single positive integer:
```java
public class MatrixToIntegerConverter {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int number = convertMatrixToInteg... | 1,802 |
Create a Java program to find the maximum element of an array that also meets the following criteria:
1. The maximum element must be odd.
2. The maximum element must be a prime number.
3. The program must not use any built-in Java libraries or methods for finding prime numbers.
4. The program must have a time complexit... | Here is an example implementation of a Java program that meets the given criteria:
```java
import java.util.ArrayList;
import java.util.List;
public class MaximumElementFinder {
public static void main(String[] args) {
// Create an array with at least 10000 elements
int[] arr = new int[10000];
// ...... | 1,901 |
Write a method which takes 4 parameters: a positive integer, a negative integer, a floating-point number, and a string. The method should return the sum of the positive integer and the negative integer, rounded to the nearest integer. However, if the floating-point number is negative, or if the string contains any spec... | Here is a method that satisfies the given requirements:
```java
public static String calculateSum(int positiveInt, int negativeInt, double floatingPoint, String text) {
// Check if any of the parameters are out of range
if (positiveInt < -1000 || positiveInt > 1000 || negativeInt < -1000 || negativeInt > 1000 ... | 1,964 |
Write a Java program to convert a binary string to a decimal number. The binary string can have a maximum length of 128 characters. Additionally, the program should handle cases where the binary string contains leading or trailing whitespace characters.
#Additional Requirements#
1. The program should validate that the... | Here is a Java program that fulfills all the additional requirements:
```java
public class BinaryToDecimalConverter {
public static int convertBinaryToDecimal(String binaryString) {
binaryString = binaryString.trim();
validateBinaryString(binaryString);
boolean isNegative = false;
... | 2,042 |
Write a Java program to multiply two large numbers of any length, but without using the `*` operator or any built-in libraries for multiplication.
Note: You can assume that the two numbers will be positive and will not exceed the maximum value of `Long`.
Provide a piece of erroneous code as a reference to increase mi... | Here is the corrected code:
```java
public class Main {
public static void main(String[] args) {
String num1 = "12345678901234567890";
String num2 = "98765432109876543210";
int len1 = num1.length();
int len2 = num2.length();
int[] result = new int[len1 + len2];
fo... | 2,045 |
Create a class in Java that takes two arguments, a name of type String and an id of type int. The name should be limited to a maximum length of 15 characters and should only consist of alphabetic characters. The id should be a positive integer between 1000 and 10000.
In addition, the name should be converted to lowerc... | The code provided does not check if the id is a positive integer between 1000 and 10000. The error can be fixed by adding an additional check in the constructor:
```java
public class Person {
private String name;
private int id;
public Person(String name, int id) {
if (name.length() <= 15 && name.... | 2,057 |
Write a Java program to sort the given array of integers using Quick Sort in descending order. Implement the Quick Sort algorithm iteratively instead of recursively. The program should have a time complexity of O(nlogn) and space complexity of O(logn). Additionally, you are not allowed to use any additional data struct... | Here's the Java program that implements Quick Sort iteratively in descending order:
```java
import java.util.Arrays;
public class QuickSortIterative {
public static void quickSort(int[] arr) {
int len = arr.length;
int[] stack = new int[len];
int top = -1;
stack[++top] =... | 2,138 |
Create a Java method that takes in a two-dimensional array of integers and prints the array in a spiral order. The array will always have an odd number of rows and columns. The method should start printing from the top left element and move in a clockwise direction. Additionally, the method should also return the sum o... | Here is the Java method that fulfills the requirements:
```java
public static int printSpiral(int[][] array) {
int sum = 0;
int rows = array.length;
int cols = array[0].length;
int top = 0;
int bottom = rows - 1;
int left = 0;
int right = cols - 1;
while (top <= bottom && left <= right... | 2,327 |
Create a loop in Java for printing all elements of an array of strings in reverse order, while also ignoring any elements that contain a specific character. The array is given below:
["String4", "String3", "String2", "String1", "Hello_World"]
New Requirements:
1. The solution should be implemented using a recursive m... | Here's a solution that meets all the given requirements:
```java
public class ReverseArray {
private static int ignoredCount = 0;
public static void main(String[] args) {
// Checking if the specific character is provided as a command-line argument
if (args.length < 1) {
System.out.println("Plea... | 2,342 |
Write a code in Java to find the factorial of a number using recursion. However, you are not allowed to use the '*' operator to multiply numbers. Instead, you should implement your own recursive multiplication method to calculate the factorial.
Additionally, you should optimize your code to handle larger numbers effic... | Here is an implementation of the factorial calculation using recursion and a custom multiplication method. It also handles negative numbers, zero, and uses memoization to improve efficiency:
```java
import java.util.HashMap;
import java.util.Map;
public class Factorial {
private static Map<Integer, Long> memo = n... | 2,350 |
Generate a random alphanumeric string of length n in Java, where n is an input provided by the user. The generated string should include at least one uppercase letter, one lowercase letter, one digit, and one special character. The time complexity of the solution should be O(n), and the space complexity should be O(1).... | Here's a possible solution to the modified problem:
```java
import java.util.Random;
public class RandomAlphanumericStringGenerator {
private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static f... | 2,381 |
Create a Java object for a student with the fields 'Name', 'Marks', 'Attendance', and 'ExtraCurricularActivities'. The 'Attendance' field should be a list of integers representing the student's attendance record for each class. The 'Marks' field should be a map where the key is the subject name (String) and the value i... | Here is a Java class representing a student with the given fields and methods:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Student {
private String name;
private Map<String, List<Integer>> marks;
private List<Integer> attendance;
... | 2,427 |
Create a method in Java to read input from the console and handle different types of input, including integers, floating-point numbers, and strings. The method should validate the input against specific criteria for each type, as follows:
- If the user enters an integer, the method should return the integer and valida... | Here's an example implementation of the method in Java:
```java
import java.util.Scanner;
public class ConsoleInputHandler {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Object userInput = readInput(scanner);
System.out.println("User input: " + userInp... | 2,545 |
Create a class in Java to store student information such as name, age, course, and grade point average. Implement a method that calculates the student's cumulative GPA by taking into account the credits earned for each course. The GPA should be rounded to two decimal places. Additionally, include a method that returns ... | Here is an implementation of the class in Java:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Student {
private String name;
private int age;
private String course;
private double gpa;
public Student(String name,... | 2,639 |
Create a Java program to print a square diamond pattern with '*' characters. However, the program should only print the diamond pattern if the input number is prime, falls within the range of 1 to 1000, and is a multiple of 3. Additionally, the program should also include a method to check if a given number is a perfec... | Here is a Java program that meets the given requirements:
```java
import java.util.Scanner;
public class SquareDiamondPattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
... | 2,793 |
Create an array of 1 million elements using Java and initialize each element with a unique value. The unique values should be randomly generated within a specified range. Additionally, ensure that the generated values are prime numbers. | Here's a Java code snippet that creates an array of 1 million elements, with each element initialized with a unique prime number randomly generated within a specified range.
```java
import java.util.Arrays;
import java.util.Random;
public class PrimeNumberArray {
public static void main(String[] args) {
i... | 2,821 |
Generate a Java program that prints the longest palindrome word in a sentence, considering that the sentence may contain multiple palindrome words with the same length. If there are multiple longest palindrome words, the program should print all of them. Additionally, the program should ignore any punctuation marks and... | Here is a Java program that finds and prints the longest palindrome word(s) in a sentence, ignoring punctuation marks and whitespace characters:
```java
import java.util.ArrayList;
import java.util.List;
public class LongestPalindrome {
public static void main(String[] args) {
String sentence = "A man, a ... | 2,852 |
Write a Java method that takes two positive integers less than or equal to 1,000,000 and returns the sum of their digits. The method should also handle negative integers and zero as input, returning -1 for negative integers and 0 for zero input.
Additionally, the method should check if the input integers are prime num... | Here's a possible implementation of the Java method:
```java
public static int sumOfDigits(int num1, int num2) {
if (num1 < 0 || num2 < 0) {
return -1; // Return -1 for negative integers
} else if (num1 == 0 || num2 == 0) {
return 0; // Return 0 for zero input
} else {
int sum = 0;
... | 2,999 |
Write Java code for converting a string to an array, but exclude any vowels and special characters from the resulting array. Additionally, remove any duplicate elements from the array and sort the array in ascending order.
String: "Hello @#& World" | Here's a Java code that converts the given string to an array, excluding vowels and special characters, removing duplicate elements, and sorting the array in ascending order:
```java
import java.util.Arrays;
import java.util.HashSet;
public class StringToArray {
public static void main(String[] args) {
St... | 3,078 |
Write a Java program to create a thread which prints the prime numbers between 1 and 1000 in ascending order, but only considers numbers that are palindromic. Additionally, the program should display a message "Thread is interrupted" if the thread is interrupted before completing its task. | Here is a Java program that creates a thread to print the palindromic prime numbers between 1 and 1000 in ascending order. It also handles the case when the thread is interrupted:
```java
public class PalindromicPrimeThread extends Thread {
@Override
public void run() {
try {
for (int i = 1... | 3,081 |
Write a Java program to compare two strings lexicographically and return the index of the first different character. Two strings: string1="GeeksforGeeks" and string2="GeeksGforGeks". Use a nested loop to compare each character of the two strings. If a different character is found, return its index. If the strings are e... | Here is the Java program that compares two strings lexicographically and returns the index of the first different character:
```java
public class CompareStrings {
public static int compareStrings(String string1, String string2) {
// Check if either string is null
if (string1 == null || string2 == n... | 3,101 |
Write a code in Java to find all the prime numbers between 0 and n, where n can be as large as 10^9. Additionally, the code should be optimized to run within a time complexity of O(nlog(logn)). The code should also handle cases where n is negative or zero by displaying an error message. | Here's a code in Java that finds all prime numbers between 0 and n, with a time complexity of O(nlog(logn)). It also handles cases where n is negative or zero by displaying an error message:
```java
import java.util.ArrayList;
public class PrimeNumbers {
public static void main(String[] args) {
int n = 10... | 3,149 |
Implement a password validator in Java that meets the following requirements:
- The password must contain at least two uppercase letters.
- The password must contain at least two lowercase letters.
- The password must contain at least two digits.
- The password must contain at least two special characters (!, @, #, $, ... | Here is a possible implementation of the password validator in Java:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordValidator {
public static boolean validatePassword(String password) {
// Check length
if (password.length() < 10 || password.length... | 3,151 |
Create an array in Java that contains ten elements, each of type String. Additionally, ensure that each element in the array is unique, contains only lowercase alphabets, and is sorted in ascending order. | Here's an example of how you can create an array in Java that meets all the given requirements:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "cherry", "grape", "kiwi", "mango", "orange", "peach", "pear", "strawberry"};
... | 3,209 |
Write a Java program that asks the user to input a character and then performs the following operations on it:
1. Check if the character is a letter (either uppercase or lowercase).
2. If it is a letter, determine if it is a vowel or a consonant.
3. If it is a vowel, display a message saying "The entered character is a... | Here is the Java program that fulfills the given requirements:
```java
import java.util.Scanner;
public class CharacterOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a character:");
String input = scanner.nextLine(... | 3,283 |
Write a Java code to perform binary search on the given sorted array. The code should handle cases where the array may contain duplicate elements. Additionally, the code should return the index of the first occurrence of the target element in the array. | Here is the Java code that performs a binary search on a given sorted array and returns the index of the first occurrence of the target element:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
int result =... | 3,343 |
Write a Java method that takes in a string and returns an array containing all the possible permutations of this string. Additionally, each permutation should only contain unique characters. The time complexity of the algorithm should be less than O(n!), where n is the length of the string.
You are not allowed to use ... | Here's one possible solution to the problem:
```java
import java.util.ArrayList;
public class Permutations {
public static ArrayList<String> getPermutations(String input) {
ArrayList<String> permutations = new ArrayList<>();
backtrack(permutations, new StringBuilder(), input.toCharArray(), ne... | 3,747 |
Create a Java code snippet that takes two integers as parameters and prints the larger one. Additionally, ensure that the program handles and outputs an error message if either of the input integers is negative. To further increase the difficulty, modify the code to handle the scenario where both input integers are equ... | Here's a Java code snippet that takes two integers as parameters, handles negative inputs, and prints the larger one. It also handles the scenario where both input integers are equal and prints a message indicating this. The code uses a ternary operator to minimize the number of comparisons performed.
```java
public c... | 3,764 |
Create a conditional statement in Java that prints "Welcome!" if the given argument is "Hi" and the length of the argument is a prime number. Also, ensure that the code throws a custom exception called "InvalidLengthException" and handles it properly if the argument is null or if the length of the argument is not a pos... | Here is a code snippet that fulfills the given requirements:
```java
public class Main {
public static void main(String[] args) {
String input = "Hi"; // Change the input as desired
try {
if (input == null || input.length() <= 0) {
throw new InvalidLengthException("Inva... | 3,860 |
Create a program in Java to check whether the given sentence is a palindrome or not. The program should ignore any whitespace characters, punctuation marks, and special characters in the input sentence. Additionally, the program should be case-insensitive. The input sentence will only contain alphanumeric characters, w... | Here's a program that meets the requirements:
```java
import java.util.Scanner;
public class PalindromeChecker {
public static boolean isPalindrome(String sentence) {
// Remove whitespace characters, punctuation marks, and special characters
sentence = sentence.replaceAll("[^a-zA-Z0-9]", "").toLow... | 3,867 |
Create a Java program to list out all prime numbers between m and n, where m and n are positive integers less than or equal to 100. Additionally, the program should display the product of all prime numbers found. Implement the program using a multi-threaded approach, where each thread is responsible for finding prime n... | Here's a Java program that lists all prime numbers between m and n using a multi-threaded approach:
```java
import java.util.ArrayList;
import java.util.List;
class PrimeThread extends Thread {
private int start;
private int end;
private List<Integer> primes;
public PrimeThread(int start, int end... | 3,910 |
Write a Java program to print the first ten Fibonacci numbers using a for loop. | Here is a Java program that prints the first ten Fibonacci numbers using a for loop:
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int[] fibonacci = new int[n];
// Set the first two numbers in the sequence
fibonacci[0] = 0;
fi... | 3,939 |
Write a Java program that searches an array for a given value and returns the index at which it is found. The array contains unique integers in ascending order. Implement a modified binary search algorithm to solve this problem.
Additionally, the program should handle the case when the array contains duplicate values.... | Here is a possible implementation of the Java program:
```java
public class BinarySearch {
public static int modifiedBinarySearch(int[] arr, int searchValue) {
int low = 0;
int high = arr.length - 1;
int result = -1;
while (low <= high) {
int mid = low + (high - low) / ... | 3,982 |
Construct a Java program to determine whether a given number is a palindrome. A palindrome number is a number that remains the same when its digits are reversed.
#Example#
Number: 121
Output: The number is a palindrome.
Number: 123
Output: The number is not a palindrome. | Here is the Java program to determine whether a given number is a palindrome:
```java
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.next... | 4,034 |
Write a Java program to print the frequencies of all characters in a string. However, you must implement this program using only arrays or primitive data types, without using any built-in data structures like maps or hash tables. Additionally, the program should have a time complexity of O(n) and a space complexity of ... | Here is a possible implementation of the program:
```java
public class CharacterFrequency {
public static void main(String[] args) {
String input = "aAbcDd";
int[] frequency = new int[26]; // Array to store the frequency of each character (a-z)
// Iterate through each character in the str... | 4,138 |
Write code in Java to find the sum of all the prime numbers in an array. The array can contain both positive and negative integers. The array can have a maximum length of 1000. The code should handle cases where the array is empty or contains only one element. | Here's the code in Java to find the sum of all prime numbers in an array:
```java
public class SumOfPrimesInArray {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
... | 4,181 |
Write a Java program that generates a random value from 1 to 100, checks if it is a prime number, and if it is a prime number, it should print "Prime number". If it is not a prime number, it should print "Not a prime number". | Sure, here's a Java program that generates a random value from 1 to 100, checks if it is a prime number, and prints the corresponding result:
```java
import java.util.Random;
public class PrimeNumberChecker {
public static void main(String[] args) {
Random random = new Random();
int randomNumber =... | 4,186 |
Create a Java method which takes a String and an integer as inputs and concatenates the integer to the beginning of the string. The integer must be positive, less than 1000, should not contain any digit more than once, and must have the digits arranged in descending order. | Here's an example of a Java method that meets your requirements:
```java
public String concatenateInteger(String str, int num) {
if (num < 1 || num >= 1000) {
throw new IllegalArgumentException("The integer must be positive and less than 1000.");
}
String numStr = String.valueOf(num);
... | 4,210 |
Create a Java method to print a binary tree in level order, but without using any additional data structures or recursion. Additionally, the tree may contain duplicate values, and you should print the duplicate nodes only once in level order traversal. Furthermore, you must implement a solution with a time complexity o... | Here's an implementation of the level order traversal of a binary tree without using additional data structures or recursion, while also taking care of duplicate nodes:
```java
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(i... | 4,271 |
Create a method to validate an email address in Java that also checks if the email address is from a specific subdomain (e.g., subdomain.example.com). Additionally, the method should validate the format of the email address according to the RFC 5322 standard and should reject any email addresses that contain special ch... | Here's an example of a method in Java that validates an email address according to the RFC 5322 standard, checks if it is from a specific subdomain, and rejects any email addresses containing special characters:
```java
import java.util.regex.Pattern;
public class EmailValidator {
private static final String EMAI... | 4,291 |
Create a multithreaded program that logs the time a user entered a program and calculates the duration of their session in minutes. Additionally, implement a feature that allows the user to enter their name and display a personalized welcome message upon entering the program. The program should also enforce a maximum s... | Here is an example of a multithreaded program that meets the provided requirements:
```java
import java.util.*;
import java.text.SimpleDateFormat;
class User {
private String name;
private Date startTime;
private Date endTime;
public User(String name) {
this.name = name;
this.startTim... | 4,368 |
Create a Java program that calculates the probability of rolling a pair of dice and getting a sum greater than or equal to 8 and less than or equal to 12, but with the constraint that the sum must also be divisible by 3 and the numbers on the dice must be prime numbers. | Here's a Java program that calculates the probability of rolling a pair of dice and getting a sum greater than or equal to 8 and less than or equal to 12, with the additional constraints that the sum must be divisible by 3 and the numbers on the dice must be prime numbers:
```java
public class DiceProbability {
p... | 4,387 |
Write a Java Program to print the Fibonacci numbers for a given range, with the additional requirement that the program must be implemented using a recursive approach. Additionally, the program should include error handling to handle invalid input and gracefully display an error message. Furthermore, the program should... | Here is a Java program that prints the Fibonacci numbers for a given range using a recursive approach with optimized efficiency and error handling:
```java
import java.util.Scanner;
public class FibonacciRecursive {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
... | 4,392 |
Write a Java code to calculate the sum of two numbers provided as input. Additionally, you must check if the sum is divisible by both 3 and 5. If it is divisible by both, print "Divisible by both 3 and 5" as the output; if it is divisible by only one of them, print "Divisible by 3 or 5"; otherwise, print "Not divisible... | Here is a Java code that calculates the sum of two numbers, checks if the sum is divisible by both 3 and 5, checks if the sum is prime, and prints the appropriate message based on the conditions provided:
```java
import java.util.Scanner;
public class SumDivisiblePrime {
public static void main(String[] args) {
... | 4,459 |
Construct a java method to convert a string to a camel case format and count the number of occurrences of each word in the string, while ignoring any stop words.
String str = "this is a great day"
Stop words: "is", "a"
Requirements:
- The method should have a time complexity of O(n), where n is the length of the inpu... | Here's a Java method that fulfills the given requirements:
```java
import java.util.HashMap;
public class StringConverter {
public static HashMap<String, Integer> convertToCamelCaseAndCount(String str, String[] stopWords) {
// Convert the string to camel case format and count word occurrences
String[] wo... | 4,469 |
Implement a switch-case statement in Java that takes in a string as input and performs different operations based on the value of the string.
Requirements:
- The input string can only contain lowercase alphabets (a-z).
- The switch-case statement should handle at least 20 different cases.
- Each case should perform a ... | Here is an example implementation of a switch-case statement in Java that satisfies the requirements:
```java
import java.util.HashMap;
import java.util.Map;
class MySwitchCase {
private Map<Character, Operation> operationMap;
// Custom exception for invalid characters
class InvalidCharacterException ext... | 4,544 |
Write a Java program to print a right triangle star pattern with a given base, where each row contains a number sequence. The number sequence should start from 1 and increment by a given odd number for each row. The triangle should be centered and have alternating colors for the number sequence. Additionally, the progr... | Here is a Java program that prints a right triangle star pattern with a given base, where each row contains a number sequence. The program also keeps track of the total sum of the number sequence for each row and displays it at the end.
```java
import java.util.Scanner;
public class RightTrianglePattern {
public ... | 4,571 |
Write a Java code snippet to calculate the area of a triangle, given three points. The points should not be collinear and should lie on a 2D plane.
x1, y1 = -2.5, 3.7
x2, y2 = 1.8, -4.2
x3, y3 = 6.3, 1.9
The code should handle the case when the points are collinear and output an appropriate message. Additionally, the... | Here's the Java code snippet that calculates the area of a triangle given three points:
```java
public class TriangleAreaCalculator {
public static void main(String[] args) {
double x1 = -2.5;
double y1 = 3.7;
double x2 = 1.8;
double y2 = -4.2;
double x3 = 6.3;
doubl... | 4,648 |
Create a singly linked list in Java and add the following elements: 5, 7, 3, 9, 2, 6. Sort the linked list in descending order using a merge sort algorithm and then print the elements in reverse order. | Here's an example of creating a singly linked list in Java, adding the given elements, sorting it in descending order using merge sort algorithm, and then printing the elements in reverse order:
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next =... | 4,768 |
Create a Java program to print out the number of times a specific word appears in an array of sentences. The program should also consider variations in capitalization, meaning "Apple" and "apple" should be considered the same word. The program should have a time complexity of O(n), where n is the total number of charac... | Here's a Java program that meets the given requirements:
```java
import java.util.HashMap;
import java.util.Map;
public class WordCounter {
public static void main(String[] args) {
String[] sentences = {"This is a test sentence.", "Another sentence!", "Test test test"};
String[] words = {"test", "... | 4,769 |
Create a variable in Java for storing a user's first name and ensure that the first name has a minimum length of 3 characters and a maximum length of 20 characters. Additionally, implement a validation mechanism to check that the first name consists only of alphabetic characters (A-Z, a-z). The first name should not co... | Here's an example of how you can create a variable to store a user's first name in Java and implement the validation mechanism:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your fir... | 4,985 |
Generate a valid Java code for a nested for loop to print all possible combinations of three letters from the English alphabet, but exclude any combinations that contain the letter 'e' or 'o'. Additionally, the letters must be printed in ascending order and should not repeat within each combination. | Here's a valid Java code for a nested for loop to print all possible combinations of three letters from the English alphabet, excluding combinations that contain the letter 'e' or 'o', while ensuring that the letters are printed in ascending order and do not repeat within each combination:
```java
public class Combina... | 5,028 |
Create a method that given an array of integers as input, outputs the quantity of odd numbers that are greater than 10 and divisible by 3. The method should also handle any potential errors that may occur during the execution, such as empty array input, invalid array elements, and an additional requirement that the met... | Here's a recursive method in Java that meets the given requirements:
```java
public static int countOddNumbersGreaterThan10AndDivisibleBy3(int[] arr) {
return countOddNumbersGreaterThan10AndDivisibleBy3(arr, 0);
}
private static int countOddNumbersGreaterThan10AndDivisibleBy3(int[] arr, int index) {
if (arr =... | 5,085 |
Write a Java code to clone a linked list using recursion. The original linked list contains nodes with both integer values and strings. Additionally, you should implement a method to reverse the cloned linked list using a doubly linked list.
The time complexity of both cloning and reversing the linked list should be O... | Here is a possible implementation:
```java
class Node {
int intValue;
String stringValue;
Node next;
Node prev;
Node(int intValue, String stringValue) {
this.intValue = intValue;
this.stringValue = stringValue;
this.next = null;
this.prev = null;
}
}
class Link... | 5,114 |
Write a Java code to generate a Fibonacci number at a given index. The code should utilize recursion to solve the problem and have a time complexity of O(n). Additionally, the code should handle edge cases such as negative indices, large indices that may cause overflow, and optimize the solution by using memoization to... | Corrected Code:
```java
public class Fibonacci {
public static long fibonacci(int n) {
if (n < 0) {
throw new IllegalArgumentException("Index cannot be negative.");
} else if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
... | 5,156 |
Write a Java program that finds the first 100 prime numbers, starting from 2. The program should include error handling to handle invalid input and display an appropriate error message. Additionally, the program should have a time complexity of O(n log(log n)), where n is the input number.
Provide a piece of erroneou... | Here is the Java program that finds the first 100 prime numbers, starting from 2, with error handling for invalid input:
```java
public class PrimeNumberFinder {
public static void main(String[] args) {
int count = 0;
int number = 2;
while (count < 100) {
if (isPrime(nu... | 5,196 |
Create a Java program that takes an array of n elements (where n > 10^6) and prints out the sum of the three largest distinct values. The program should also handle cases where there are duplicate elements in the array.
Example input:
[10^9, 10^8, 10^7, ..., 3, 2, 1, 10^9, 10^8, 10^7, ..., 3, 2, 1]
Expected output:
S... | Here's the corrected code:
```java
public class Main {
public static void main(String[] args) {
int[] arr = {10^9, 10^8, 10^7, ..., 3, 2, 1, 10^9, 10^8, 10^7, ..., 3, 2, 1};
int n = arr.length;
if(n <= 3) {
System.out.println("Array must have more than 3 elements");
... | 5,229 |
Create a program in Java to print the sum of all Fibonacci numbers within the given range.
## Requirements:
- The program should be able to handle large ranges efficiently, with a range of up to 1 million.
- The program should have a time complexity of O(n) and a space complexity of O(1).
Erroneous Code Reference:
`... | The error in the given code is that it is calculating the sum of all Fibonacci numbers within the range, instead of just the Fibonacci numbers themselves.
To fix this, we need to modify the second for loop to only calculate the sum of the Fibonacci numbers. We can do this by checking if the current number in the Fibo... | 5,270 |
Write a Java program to print the nth prime number, without using recursion, an iterative loop, or an array to store previous values. | Here is a Java program that prints the nth prime number without using recursion, an iterative loop, or an array to store previous values:
```java
public class NthPrimeNumber {
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Ma... | 5,305 |
Construct an array in Java containing the first 1000 prime numbers and calculate the sum of all the prime numbers in the array. | To solve this task, we can create a method that checks whether a number is prime or not. Then, we can use a loop to find the first 1000 prime numbers and store them in an array. Finally, we calculate the sum of all the prime numbers in the array. Here's the code:
```java
public class PrimeNumberArray {
public stat... | 5,343 |
Generate a Java program to perform the following task.
Given a list of integers, find the sum of all the prime numbers in the list and print the result. The program should also handle the case when the list is empty and display a message indicating that there are no prime numbers in the list. | Here's a Java program that accomplishes the task:
```java
import java.util.ArrayList;
import java.util.List;
public class PrimeNumberSum {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(4);
numbers.add(6);
... | 5,365 |
Generate a class in Java that validates if a given number is a prime or not. The number must be between 1 and 10,000,000, and the class should handle input numbers efficiently within a time complexity of O(sqrt(n)).
The class should implement an optimized algorithm for checking if a number is prime, such as the Sieve ... | Here's an implementation of the requested class in Java:
```java
import java.util.ArrayList;
import java.util.List;
public class PrimeNumberValidator {
private static final int MAX_PRIME_CHECK = 10000000;
private static final int MAX_PRIME_GENERATION = 1000000000;
private static final int MAX_PRIME_SUM_RA... | 5,390 |
Write a Java program to calculate the sum of the series 1^3+2^3+3^3+.....+n^3, where n must be a positive integer less than or equal to 100. The program should also check if the input is valid and display an error message if it is not. Additionally, the program should print the sum in both decimal and binary representa... | Here is a Java program that calculates the sum of the series 1^3 + 2^3 + 3^3 + ... + n^3, where n is a positive integer less than or equal to 100:
```java
import java.util.Scanner;
public class SeriesSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out... | 5,413 |
Write a Java program to implement a binary search on a sorted array of integers. However, instead of searching for a specific element, the program should find the index of the smallest element that is greater than or equal to a given target element. If the target element is greater than all elements in the array, the p... | Here is a possible solution to implement a binary search algorithm in Java to find the index of the smallest element that is greater than or equal to a given target element:
```java
public class BinarySearch {
public static int search(int[] arr, int target) {
return binarySearch(arr, target, 0, arr.length ... | 5,436 |
Create a method in Java called `checkNumber` that takes an integer as a parameter and returns a boolean value indicating whether the number is divisible by both 3 and 5. The method should also check if the number is greater than 100 and less than 1000. If the number is not within this range, the method should throw an ... | Here is a code snippet to test the `checkNumber` method:
```java
public static void main(String[] args) {
// Test with values less than 100
try {
checkNumber(50);
System.out.println("50 is divisible by 3 and 5");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage... | 5,521 |
Create a Java class for car objects that includes the following features:
1. Implement a constructor that takes parameters for the car's make, model, year of manufacture, color, and maximum speed limit.
2. Include private instance variables for the car's make, model, year of manufacture, color, current speed, and ma... | Here is a Java class for car objects that includes the requested features:
```java
public class Car {
private String make;
private String model;
private int year;
private String color;
private int currentSpeed;
private int maxSpeedLimit;
public Car(String make, String model, int year, Stri... | 5,604 |
Write a Java program to read a text document and count the number of unique words in the given document. However, the program should ignore any words that are enclosed within quotation marks or any special characters, and consider only distinct words.
To solve this problem, the program should:
1. Prompt the user to en... | Here is the Java program to solve the problem:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class UniqueWordCounter {
public static void main(String[] args) {
try {
// Prompt the user to ent... | 6,074 |
Create a Java class to represent a point in 2D space using two fields, x and y. The x and y values should be restricted to prime numbers between -100 and 100, inclusive. Additionally, the class should have a method to calculate the distance between two points in 2D space, but the distance calculation should only consid... | Here is an example implementation of the Java class representing a point in 2D space with the additional requirements:
```java
import java.util.Objects;
class PrimeNumberException extends Exception {
public PrimeNumberException(String message) {
super(message);
}
}
class InvalidPointException extends... | 6,148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.