code stringlengths 160 48.7k | prompt stringlengths 38 3.13k |
|---|---|
Here is an example of a Java method that checks whether an integer is a prime number or not:
```java
public class PrimeNumberChecker {
public static boolean isPrime(int number) {
// check for negative input, zero, and one
if (number <= 1) {
return false;
}
// ch... | 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. |
Here is a 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 scanner = new Scanner(System.in);
System.out.print("Enter a number: ");... | 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... |
Sure! Here's a Java program that compares two strings for equality, considering case sensitivity, leading/trailing whitespaces, and the presence of special characters such as punctuation marks and symbols. The program also handles Unicode characters.
```java
import java.text.Normalizer;
import java.util.regex.Pattern;... | Generate a Java program for comparing two strings for equality, considering case sensitivity, leading/trailing whitespaces, and the presence of special characters such as punctuation marks and symbols. The program should also handle Unicode characters. |
Here's a Java code snippet that generates a random integer between 1 and 1000, but only multiples of 5:
```java
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random rand = new Random();
int randomNumber;
do {
randomNumbe... | Create a random number generator in Java that produces a random integer between 1 and 1000, but only multiples of 5. |
Here is an example implementation of a Java thread that follows the steps you provided:
```java
import java.util.Random;
import java.util.Scanner;
public class DivisibleThread extends Thread {
private boolean running = true;
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
... | Create a new Java thread that performs the following steps:
1. Prompt the user to enter a number between 1 and 100.
2. Read the input number from the user.
3. Check if the number is divisible by 2 and 3.
4. If the number is divisible by 2 and 3, print "Divisible by 2 and 3" to the console.
5. If the number is divisible... |
Here is a Java class that prints "Welcome to my program" if the current date is a prime number and the hour is a prime number:
```java
import java.util.Calendar;
public class PrimeNumberProgram {
public PrimeNumberProgram() {
// Get the current date and hour
Calendar calendar = Calendar.getInstanc... | Create a Java class that prints "Welcome to my program" when initialized, but only if the current date is a prime number and the hour is a prime number. |
Here is a declaration in Java to store the coordinates of a point in 3D space using polar coordinates:
```java
public class Point3D {
private double radius;
private double theta;
private double phi;
public Point3D(double radius, double theta, double phi) {
this.radius = radius;
this.th... | Construct a declaration in Java to store the coordinates of a point in 3D space, with the additional requirement that the coordinates must be represented using polar coordinates. Implement a method that calculates the distance between two points in 3D space using the polar coordinates. |
Here's a Java program that meets the given constraints:
```java
public class CombinationGenerator {
public static void main(String[] args) {
generateCombinations("", 0);
}
public static void generateCombinations(String prefix, int digit) {
System.out.println(prefix + digit);
if (... | Write a Java program to print out all possible combinations of the numbers from 0 to 9 in ascending order, without using any loop statements.
Additional Constraints:
- The program should use recursion to generate the combinations.
- The program should output the combinations in lexicographical order.
- The program sho... |
Here's a program in Java that checks if a given number is prime or not, and displays all prime numbers between 1 and 100. It also allows the user to input a range and displays all prime numbers within that range.
```java
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) ... | Create a program in Java that checks if a given number is prime or not, and displays all prime numbers between 1 and 100. Additionally, modify the program to accept a range of numbers from the user and display all prime numbers within that range.
Increase the difficulty by:
1. Adding a requirement to use multi-thread... |
Here is a code example that constructs an array of size 10, initializes it with random numbers between 1 and 1000, calculates the sum of all the prime numbers in the array, and displays the result:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] numbers ... | Construct an array of size 10 to store integers in Java. Initialize the array with random numbers between 1 and 1000. Calculate the sum of all the prime numbers in the array and display the result. |
Here's a Java program that takes a two-dimensional array of integers as input and calculates the sum of all its elements using a nested for loop. It also tracks and prints the average of all the elements in the array:
```java
import java.util.Scanner;
public class ArraySumAndAverage {
public static void main(Stri... | 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. |
Here's an example code to create an array in Java to store the first 100 prime numbers:
```java
public class PrimeNumbers {
public static void main(String[] args) {
int[] primeNumbers = new int[100];
int count = 0;
int number = 2;
while (count < 100) {
if (isPrime(numbe... | Create an array in Java to store the first 100 prime numbers. |
Here is a possible implementation of the method:
```java
public static int removeDuplicates(int[] nums) {
int length = nums.length;
if (length == 0 || length == 1) {
return length;
}
int index = 1;
for (int i = 1; i < length; i++) {
int j;
for (j = 0; j < i; j++) {... | 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 an example of a program that calculates the sum of elements in a 2D array while handling potential runtime errors:
```java
public class ArraySumCalculator {
public static void main(String[] args) {
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
try {
int sum = calculateAr... | Generate a syntax-correct program to calculate the sum of the elements in a given 2D array, but ensure that the program also checks for and handles any potential runtime errors, such as a null array, an array with mismatched dimensions, or an array containing non-numeric values. Additionally, implement the program in a... |
Here is one possible implementation:
```java
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
```
... | 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 is an example of a switch statement in Java that displays the corresponding number in words between 1 and 1000 (inclusive), with error handling for numbers outside this range:
```java
public class NumberToWordConverter {
public static void main(String[] args) {
int number = 567; // Example number
... | 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. |
Here is a possible implementation of the data structure in Java:
```java
import java.util.*;
class Book {
private String isbn;
private String authors;
private String publicationDate;
private int numberOfPages;
public Book(String isbn, String authors, String publicationDate, int numberOfPages) {
... | 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 a Java class that finds all distinct substrings of a given string without any repeating characters:
```java
import java.util.HashSet;
public class DistinctSubstrings {
public static void main(String[] args) {
String input = "Hello World";
printDistinctSubstrings(input);
}
public s... | 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.
Example:
Input: "Hello World"
Output: "H", "He", "Hel", "Hell", "Hello", "... |
Here is the implementation of the "Card" class:
```java
public class Card {
private String suit;
private int number;
public Card(String suit, int number) {
if (!isValidSuit(suit)) {
throw new IllegalArgumentException("Invalid suit. Valid suits are: Spades, Hearts, Diamonds, Clubs");
... | Create a Java class named "Card" to represent a standard playing card. The class should contain a constructor which takes the card's suit and number as parameters. The suit should be a string that can only be one of the following: "Spades", "Hearts", "Diamonds", "Clubs". The number should be an integer between 1 and 13... |
Here's a Java program that finds the kth smallest element in an unsorted array of integers, with a time complexity of O(n log k):
```java
import java.util.PriorityQueue;
public class KthSmallestElement {
public static int findKthSmallest(int[] nums, int k) {
// Create a max heap using PriorityQueue
... | Write a Java program to find the kth smallest element in an unsorted array of integers, where k is a positive integer less than or equal to the length of the array. Additionally, your program should have a time complexity of O(n log k), where n is the length of the array. |
Here's the correct code for the nested for loop:
```java
for(int i = 0; i >= -10; i *= 3) {
for(int j = 1; j <= i; j++) {
System.out.println("Outer loop: " + i + ", Inner loop: " + j);
}
}
```
This code will iterate over the outer loop from 1 to 5, and for each iteration, it will iterate over the inne... | 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 5, and the inner loop should iterate from 1 to the current value of the outer loop co... |
Here's a Java method that swaps the values of two integer variables without using a temporary variable and handles the case where the input integers are equal:
```java
public static void swapIntegers(int a, int b) {
if (a == b) {
System.out.println("Error: The input integers are equal.");
return;
... | 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. |
Here's an example implementation of a Java class that computes the sum of the cube of even prime numbers between k and n efficiently:
```java
import java.math.BigInteger;
public class EvenPrimeCubesSum {
public static BigInteger computeSumOfEvenPrimeCubes(int k, int n) {
BigInteger sum = BigInteger.ZERO;
... | Create a class in Java which computes the sum of the cube of even 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. |
Here is an example of a Java program that accepts user input for an array of integers and passes it to a method. The method then calculates the product of all the prime numbers in the array and prints the result:
```java
import java.util.Scanner;
public class PrimeProduct {
public static void main(String[] args) ... | Write a Java program that accepts user input for an array of integers and passes it to a method. The method should return the product of all the prime numbers in the array and print the result. |
Here is a Java program that calculates the sum of the given ten prime numbers:
```java
public class PrimeNumberSum {
public static void main(String[] args) {
int a = 2;
int b = 3;
int c = 5;
int d = 7;
int e = 11;
int f = 13;
int g = 17;
int h = 19;
... | Create a program using Java to print the sum of the following ten prime numbers.
int a = 2;
int b = 3;
int c = 5;
int d = 7;
int e = 11;
int f = 13;
int g = 17;
int h = 19;
int i = 23;
int j = 29; |
Here is a Java program that solves the Tower of Hanoi puzzle and calculates the minimum number of moves needed. It also allows the user to input the number of disks in the puzzle.
```java
import java.util.Scanner;
public class TowerOfHanoi {
public static void main(String[] args) {
Scanner scanner = new S... | Construct a program in Java for solving the Tower of Hanoi puzzle, with the additional requirement of finding the minimum number of moves needed to solve the puzzle. Additionally, implement a feature that allows the user to input the number of disks in the puzzle, with a minimum of 3 disks and a maximum of 10 disks. |
Here is an example of a Java class that performs the given task:
```java
public class VowelCounter {
public static void main(String[] args) {
String inputString = "Hello, World!";
int vowelCount = 0;
System.out.println("Input String: " + inputString);
// Loop through each characte... | 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 and display the vowels in uppercase. |
Here's the Java program that categorizes each of the given strings as a palindrome or not:
```java
public class PalindromeChecker {
public static void main(String[] args) {
Object[] values = {"madam", "DAD", "superman", "abcdef", 12321, 12345};
for (Object value : values) {
System.out.... | Write a Java program to categorize each of the following strings as a palindrome or not.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization.
Your program should:
1. Declare a method called "isPalindrome... |
Here's a possible implementation in Java:
```java
public static String findShortestWord(String[] words) {
String shortestWord = null;
int shortestLength = Integer.MAX_VALUE;
for (String word : words) {
// Skip words with digits, special characters, or vowels
if (word.matches(".*\\d.*")... | Create a method to find the shortest word in a given array of strings. The method should ignore any words that contain digits, special characters, or vowels. Additionally, the method should handle the case when two or more words have the same shortest length by returning the word that occurs first in the array. |
Here is a Java program that calculates the sum of all odd numbers from 1 to 1000 and prints the result:
```java
public class OddNumberSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; i += 2) {
sum += i;
}
System.out... | Write a Java program that calculates the sum of all odd numbers from 1 to 1000 and prints the result. |
Here is the Java program that meets the requirements:
```java
import java.util.Arrays;
public class PrimePower {
public static void main(String[] args) {
int[] input = {5, 2}; // Example input array
try {
int result = calculatePower(input);
System.out.println("Result: " + ... | 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 is an example implementation of the 'combine' method in Java:
```java
public static String combine(String str1, String str2) {
if (str1.length() + str2.length() <= 150) {
return str1 + str2;
} else {
int maxLength = 150 - str1.length();
return str1 + str2.substring(0, maxLength);
... | 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. |
Sure! Here's an example program in Java that demonstrates the concept of static variables in a multi-threaded environment:
```java
import java.util.concurrent.atomic.AtomicInteger;
class MyClass {
static AtomicInteger counter = new AtomicInteger(0);
static synchronized void increment() {
counter.incr... | 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 the code to print the prime numbers between 1 and 100 in descending order:
```java
public class PrimeNumbers {
public static void main(String[] args) {
for (int i = 100; i >= 1; i--) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public stat... | Create a series of nested for loops in Java to print the prime numbers between 1 and 100 in descending order on separate lines. Additionally, modify the code to skip printing any prime numbers that end with the digit 5. |
Here's a Java program that meets all the requirements:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first string: ");... | Write a Java program that prompts the user to enter two strings and outputs whether the two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of another word or phrase.
In addition to the requirements of the given test, you should now also consider the frequency of characters in t... |
Here is a Java code that creates a set from the given array using a divide and conquer algorithm:
```java
import java.util.HashSet;
import java.util.Set;
public class SetFromArray {
public static Set<Integer> createSet(int[] arr) {
return createSet(arr, 0, arr.length - 1);
}
private static Set<I... | Create a set in Java from a given array of numbers. The set should only contain unique elements in ascending order. The input array may contain negative numbers as well.
Array: [2, -3, 5, 4, -2, 3, 5, -4]
Time Complexity Requirement: O(n), where n is the number of elements in the input array.
Space Complexity Requirem... |
Here is an example of a method in Java that checks if a given integer is a prime number using O(sqrt(n)) time complexity:
```java
public class PrimeNumberChecker {
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return... | 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(sqrt(n)). |
Here is a Java code that fulfills the given requirements:
```java
import java.util.ArrayList;
import java.util.Arrays;
public class PrimeNumbers {
public static void main(String[] args) {
int[] numbers = {2, 3, 5, 6, 7, 11, 13, 17, 19, 23};
ArrayList<Integer> primeNumbers = new ArrayList<>();
... | 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. |
Here's a program that takes a string as input, reverses the order of the words while preserving the position of any punctuation marks and whitespace.
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReverseWords {
public static void main(String[] args) {
String input = ... | Write a program in Java that takes a string as input and reverses the order of the words, while preserving the position of any punctuation marks and whitespace. For example, the input "Hello, world!" should return "!dlrow ,olleH". |
Here is the implementation of the method:
```java
public class ReverseAlphabeticalString {
public static String reverseAlphabetical(String input) {
char[] chars = input.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
// Ski... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.