code stringlengths 160 48.7k | prompt stringlengths 38 3.13k |
|---|---|
Here is an example of how you can create an array of strings in Java that only contains words starting with a vowel and have a length of more than 5 characters:
```java
public class Main {
public static void main(String[] args) {
String[] words = {"apple", "banana", "orange", "elephant", "igloo", "umbrella... | Create an array of strings in Java that only contains words starting with a vowel and have a length of more than 5 characters. |
Here is the implementation of the Car class:
```java
public class Car {
private int year;
private String make;
private String model;
public Car() {
this.year = 0;
this.make = "";
this.model = "";
}
public Car(int year, String make, String model) {
this.year = y... | Write a Java class called "Car" that has the following properties:
1. A private integer variable called "year" that represents the manufacturing year of the car.
2. A private string variable called "make" that represents the brand or make of the car.
3. A private string variable called "model" that represents the mode... |
Here is a Java method that prints a two-dimensional array in a spiral order:
```java
public class SpiralOrder {
public static void printSpiral(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int top = 0, bottom = rows - 1, left = 0, right = columns - 1;
... | Create a Java method to print a two-dimensional 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. |
Here is the Java code to display the multiplication table from 1 to 20:
```java
public class MultiplicationTable {
public static void main(String[] args) {
int tableSize = 20;
displayMultiplicationTable(tableSize);
}
public static void displayMultiplicationTable(int size) {
// ... | Generate a Java code to display the multiplication table from 1 to 20, including both rows and columns.
#Additional Instructions#
1. Use nested loops to generate the multiplication table.
2. Format the output in a tabular format, with appropriate spacing between numbers.
3. Include a header row and column to label the... |
Sure! Here's an example of a loop in Java that prints all elements of an array of strings in reverse order:
```java
public class Main {
public static void main(String[] args) {
String[] arr = {"String4", "String3", "String2", "String1"};
for (int i = arr.length - 1; i >= 0; i--) {
... | Create a loop in Java for printing all elements of an array of strings in reverse order.
["String4", "String3", "String2", "String1"] |
Here's a Java code to find the factorial of a number using recursion:
```java
public class FactorialRecursion {
public static int factorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}
public static void main... | Write a code in Java to find the factorial of a number using recursion. |
Here's a Java code that generates a random alphanumeric string of length n, meeting all the given requirements:
```java
import java.util.Random;
public class RandomStringGenerator {
public static void main(String[] args) {
int n = getInputFromUser();
String randomString = generateRandomString(n);
... | 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 Java class that represents 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... | Create a Java object for a student with the fields 'Name', 'Marks', and 'Attendance'. 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 is a list of integers represen... |
Here is an example of a method that reads input from the console, handles different types of input, and validates the input according to certain criteria:
```java
import java.util.Scanner;
public class InputReader {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String... | Create a method to read in input from the console in Java, with the additional requirement that the method should be able to handle different types of input (such as integers, floating-point numbers, and strings) and validate the input according to certain criteria.
For example, the method should be able to handle the... |
Here is a Java program that generates and prints the Fibonacci series up to a given size, based on user input:
```java
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the desire... | Create a Java program to generate and print the Fibonacci series up to a given size. The program should prompt the user to enter the desired size of the series and then generate the Fibonacci series based on the input.
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones... |
Here is an example implementation of the class in Java:
```java
import java.text.DecimalFormat;
public class Student {
private String name;
private int age;
private String course;
private double cumulativeGPA;
public Student(String name, int age, String course) {
this.name = name;
... | 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 ... |
Sure! Here's a Java program that prints a square diamond pattern with '*' characters, and includes a method to check if a given number is prime. The program only prints the diamond pattern if the input number is prime.
```java
import java.util.Scanner;
public class SquareDiamondPattern {
public static void main(... | Create a Java program to print a square diamond pattern with '*' characters. However, the program should also include a method to check if a given number is prime and only print the diamond pattern if the input number is prime. |
Here is a Java program that prints the longest word(s) in a sentence:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class LongestWordFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a ... | Generate a Java program that prints the longest word in a sentence, considering that the sentence may contain multiple words with the same length. If there are multiple longest words, the program should print all of them. |
Here's an example of a for loop in Java to find the sum of the first 20 prime numbers:
```java
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 2; count < 20; i++) {
if (isPrime(i)) {
sum += i;... | Create a for loop in Java to find the sum of the first 20 prime numbers. |
Here is a Java method that inserts a given string at the beginning of every word in a given sentence:
```java
public class Main {
public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog 12345";
String insertedString = "Hello";
String result... | Write a Java method to insert a given string at the beginning of every word in a given sentence. The given sentence can contain special characters, numbers, and multiple consecutive spaces between words. The inserted string should be enclosed in square brackets.
Example:
Input:
String sentence = "The quick brown fo... |
Here is a Java method that takes an array of integers as input and returns the sum of all the even numbers in the array:
```java
public class SumOfEvenNumbers {
public static int sumOfEvenNumbers(int[] numbers) {
int sum = 0;
for (int number : numbers) {
if (number % 2 == ... | Write a Java method that takes an array of integers as input and returns the sum of all the even numbers in the array. |
Here's a Java method that takes two numbers and returns the sum of their digits:
```java
public static int sumOfDigits(int num1, int num2) {
int sum = 0;
// Calculate the sum of digits for num1
while (num1 != 0) {
int digit = num1 % 10;
sum += digit;
num1 /= 10;
}
// Calcu... | Write a Java method that takes two numbers and returns the sum of their digits. |
Here is the Java code to convert a string to an array while excluding any vowels from the resulting array:
```java
public class StringToArrayWithoutVowels {
public static void main(String[] args) {
String str = "Hello";
char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
ch... | Write Java code for converting a string to an array, but exclude any vowels from the resulting array.
String: "Hello"
# Erroneous Code #
Write Java code for converting a string to an array, but include only vowels in the resulting array.
String: "Hello" |
Here is the Java program that creates a thread to print numbers from 10 to 0 in reverse order after every 1 second:
```java
public class ReverseNumberThread extends Thread {
@Override
public void run() {
try {
for (int i = 10; i >= 0; i--) {
System.out.println(i);
... | Write a Java program to create a thread which prints the numbers from 10 to 0 in reverse order after every 1 second. Additionally, the program should display a message "Thread is interrupted" if the thread is interrupted before completing its task. |
Here is the correct code:
```java
public class StringComparison {
public static void main(String[] args) {
String string1 = "GeeksforGeeks";
String string2 = "GeeksGforGeks";
int index = compareStrings(string1, string2);
System.out.println("First different characte... | 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"
#Erroneous Code#
Write a Java program to compare two strings lexicographically. Two strings: string1="GeeksforGeeks" and string2="GeeksQu... |
Here is one way to implement a password validator in Java:
```java
import java.util.regex.Pattern;
public class PasswordValidator {
private static final String SPECIAL_CHARACTERS = "!@#$%^&*()-_+={}[]|\\:;\"'<>,.?/`";
public static boolean validatePassword(String password) {
if (password.contains(" "... | Implement a password validator in Java that meets the following requirements:
- The password must contain at least one uppercase letter.
- The password must contain at least one lowercase letter.
- The password must contain at least one digit.
- The password must contain at least one special character (!, @, #, $, %, ^... |
Here is the code in Java to find all the prime numbers between 0 and n, optimized to run within a time complexity of O(nlog(logn)):
```java
import java.util.ArrayList;
public class PrimeNumbers {
public static ArrayList<Integer> sieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n+1];
f... | 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)). |
Here is an example of how you can create an array in Java that contains five elements, each of type String, with each element being unique:
```java
public class Main {
public static void main(String[] args) {
String[] array = new String[5];
array[0] = "Element 1";
array[1] = "Eleme... | Create an array in Java that contains five elements each of type String. Additionally, ensure that each element in the array is unique. |
Here is the Java program that performs the operations as described:
```java
import java.util.Scanner;
public class CharacterCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a character: ");
String input = scanner.n... | 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 a Java program that takes three numbers and prints out the largest number:
```java
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number 1: ");
int num1 = scanner.nextInt()... | Create a Java program that takes three numbers and prints out the largest number.
Number 1: 6
Number 2: 8
Number 3: 10 |
Here is a recursive implementation of the Binary Search algorithm in Java:
```java
public class BinarySearch {
public static int binarySearch(int[] array, int target) {
return binarySearch(array, target, 0, array.length - 1);
}
private static int binarySearch(int[] array, int target, int low, int... | Write a recursive implementation of the Binary Search algorithm in Java. |
Here's a Java program that displays the list of prime numbers from 1 to 100:
```java
public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 100 are:");
for (int i = 2; i <= 100; i++) {
if (isPrime(i)) {
System... | Write a JAVA program to display the list of prime numbers from 1 to 100. |
Here is an example Java code to perform binary search on a given sorted array:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
... | Write a Java code to perform binary search on the given sorted array. |
To create an Android application that displays the current date and time in a text view and allows the user to toggle between 12-hour and 24-hour time formats, you can follow these steps:
Step 1: Set up the project
- Open Android Studio and create a new project.
- Choose an appropriate project name, package name, and ... | Write an Android application that displays the current date and time in a text view and allows the user to toggle between 12-hour and 24-hour time formats. |
Here is an example implementation of the class in Java:
```java
import java.util.ArrayList;
import java.util.List;
class Student {
private int id;
private String name;
private int grade;
public Student(int id, String name, int grade) {
this.id = id;
this.name = name;
this.grad... | Create a class in Java to store student details and implement the following methods:
1. `getAverageGrade()`: This method should calculate and return the average grade of all the students in the class. The time complexity of this method should be O(n), where n is the number of students.
2. `getTopPerformingStudent()`:... |
Here is the implementation of the Car class in Java:
```java
public class Car {
private String color;
private double fuelLevel;
public Car(String color) {
this.color = color;
this.fuelLevel = 0.0;
}
public boolean startEngine() {
if (fuelLevel > 0.5) {
System.o... | Create a class called “Car” in Java with the following attributes and methods. The Car class should have an additional attribute called "color" which represents the color of the car. The color attribute should be a String type. The Car class should also have a method called "startEngine" which starts the engine of the ... |
Sure! Here's a Java program that displays a pattern of numbers in a pyramid shape:
```java
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
int count = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
... | Write a Java program to display a pattern of numbers in a pyramid shape. |
Here is a Java code snippet that prints the line of text "Hello, World!" with the word "World" printed in reverse order:
```java
public class HelloWorld {
public static void main(String[] args) {
String message = "Hello, World!";
String[] words = message.split(" ");
StringBuilder reversedWo... | Write a Java code snippet to print the following line of text: “Hello, World!” but ensure that the word "World" is printed in reverse order. |
Here is a Java method that takes in a string and returns an array containing all the possible permutations of this string. Each permutation only contains unique characters.
```java
import java.util.ArrayList;
import java.util.List;
public class Permutations {
public static String[] getPermutations(String input) {... | 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. |
Here is the corrected version of the program to reverse a sentence while maintaining the order of the words:
```java
import java.util.Scanner;
public class ReverseSentence {
public static void main(String[] args) {
// Get input sentence from user
Scanner scanner = new Scanner(System.in);
S... | Create a program in Java to reverse a sentence while maintaining the order of the words.
For example, if the input sentence is "This is a sample sentence," the output should be "sentence sample a is This."
Provide a piece of erroneous code to mislead the candidates:
```
String[] words = sentence.split(" ");
for (int i... |
Here's the Java code snippet that takes two integers as parameters and prints the larger one, while handling and outputting an error message if either of the input integers is negative:
```java
public class Main {
public static void main(String[] args) {
int num1 = 5; // replace with desired value
... | 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. |
Here's an example of a conditional statement in Java that prints "Welcome!" if the given argument is "Hi" and the length of the argument is greater than or equal to 2:
```java
public class ConditionalStatementExample {
public static void main(String[] args) {
String argument = "Hi";
if (ar... | Create a conditional statement in Java that prints "Welcome!" if the given argument is "Hi" and the length of the argument is greater than or equal to 2. |
Here is a Java program that checks whether a given word is a palindrome or not, ignoring whitespace characters and being case-insensitive:
```java
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.ou... | Create a program in Java to check whether the given word is a palindrome or not. The program should also ignore any whitespace characters in the input word and should be case-insensitive. The input word will only contain alphabetic characters. |
Sure! Here's a Java program that lists out all prime numbers between 1 and n, where n is a positive integer less than or equal to 100. It also displays the sum of all prime numbers found.
```java
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner... | Create a Java program to list out all prime numbers between 1 and n, where n is a positive integer less than or equal to 100. Additionally, the program should display the sum of all prime numbers found. |
Here is the Java program that prints 'Hello World' five times using a for loop:
```java
public class HelloWorld {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Hello World");
}
}
}
```
When you run this program, it will print 'Hello Worl... | Write a Java program to print 'Hello World' five times using a for loop. |
Here's an implementation of the binary search algorithm in Java:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int searchValue) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
... | 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 binary search algorithm to solve this problem.
int[] arr = {3, 4, 6, 7, 8, 10};
int searchValue = 8;
#Difficulty increased#
The original test was... |
Here is the Java program to replace all occurrences of a given character with '*':
```java
public class ReplaceCharacter {
public static void main(String[] args) {
String str = "Hello World!";
char ch = 'o';
String result = replaceCharacter(str, ch);
System.out.println(result);
... | Write a Java program to replace all occurrences of a given character with '*'.
String = "Hello World!"
Character = 'o' |
Here is a Java program that uses a custom data structure to print the frequencies of all characters in a string:
```java
public class CharacterFrequencyCounter {
static class CharacterFrequency {
char character;
int frequency;
public CharacterFrequency(char character) {
this.c... | Write a java program to print the frequencies of all characters in a string. However, you must implement this program using a custom data structure instead of using any built-in data structures like maps or hash tables. |
Here's a Java code to calculate the sum of the first n Fibonacci numbers:
```java
public class FibonacciSum {
public static int fibonacciSum(int n) {
if (n <= 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
int sum = 1;
int prev1 = 1;
... | Write Java code to calculate the sum of the first n Fibonacci numbers. |
Here is a Java code to find the sum of all the unique elements in an array:
```java
import java.util.HashSet;
public class SumOfUniqueElements {
public static int sumOfUniqueElements(int[] nums) {
// Create a HashSet to store unique elements
HashSet<Integer> uniqueElements = new HashSet<>();
... | Write code in Java to find the sum of all the unique elements in an array. |
Here's the Java program that checks if t is an anagram of s:
```java
import java.util.Arrays;
public class AnagramChecker {
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26]; // Assuming only... | Create a Java program that takes two strings s and t as input and checks if t is an anagram of s. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. Your program should return true if t is an anagram of s and false otherwise.
Time Complexity Requirement: Your program should run... |
Here is a Java program that finds the common characters in two given strings and counts the frequency of each common character:
```java
import java.util.HashMap;
import java.util.Map;
public class CommonCharacters {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "wor... | Write a Java program to find the common characters in two given strings and count the frequency of each common character. |
Here is a Java method that takes a string and an integer as input and returns the string in reverse with the integer repeated at the end:
```java
public String reverseStringWithInteger(String inputString, int inputInteger) {
// Check if the input string is null or empty
if (inputString == null || inputString.i... | Write a Java method that takes a string and an integer as input, and returns the string in reverse with the integer repeated at the end. The string can contain special characters and digits, and may have a maximum length of 100 characters. The integer should be a positive number between 1 and 1000. The method should ha... |
Here is an example of an object-oriented program in Java that meets the given constraints:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
class Rectangle {
private double length;
private double width;
public double getLength() {
return length;
}
public void se... | Create an object-oriented program in Java to calculate the area and perimeter of a rectangle, with the following additional constraints:
- The program should include at least two classes, one for the rectangle and one for the main program.
- The rectangle class should have private instance variables for the length and... |
To print a binary tree in level order without using any additional data structures or recursion, you can use a queue to keep track of the nodes in each level. The algorithm follows these steps:
1. Create a queue and enqueue the root node of the binary tree.
2. While the queue is not empty, do the following:
a. Deq... | Create a Java method to print a binary tree in level order, but without using any additional data structures or recursion. |
Here's an example of a method in Java that validates an email address and also checks if it is from a specific domain:
```java
import java.util.regex.Pattern;
public class EmailValidator {
// Email validation regular expression pattern
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Z... | Create a method to validate an email address in Java that also checks if the email address is from a specific domain (e.g., example.com). |
Sure! Here's an example of a Java program that generates a random array of 1000 integers ranging from 0 to 999:
```java
import java.util.Random;
public class RandomArrayGenerator {
public static void main(String[] args) {
// Create a random object
Random random = new Random();
// Create a... | Generate a Java program that creates a random array of 1000 integers ranging from 0 to 999. |
Here's a Java method that counts the number of vowels in a given string:
```java
public static int countVowels(String input) {
// Initialize a counter variable to keep track of the number of vowels
int count = 0;
// Convert the input string to lowercase to simplify comparison
String lowercaseInput... | Write a method in Java that takes a string as input and returns the number of vowels present in the string. |
Here is 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:
```java
import java.util.Random;
public class DiceProbability {
public static void main(String[] args) {
int totalRolls = 1000000; // Number of times... | 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. |
Here is a Java program that uses a recursive approach to print the Fibonacci numbers for a given range:
```java
public class FibonacciRecursive {
public static void main(String[] args) {
int range = 10; // Set the range of Fibonacci numbers to be printed
System.out.println("Fibonacci Serie... | 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. |
To construct a regex in Java that matches a valid email address and validates the domain name, you can use the following pattern:
```java
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
```
This regex pattern consists of the following parts:
- `^` - Beginning of... | Construct a regex in Java that matches a valid email address and also validates the domain name. |
Here is a Java code that generates a square matrix of size n, fills it with randomly generated integers ranging from -100 to 100, and computes and prints the sum of the main diagonal elements in the matrix:
```java
import java.util.Random;
public class Main {
public static void main(String[] args) {
int n... | Write Java code to generate a square matrix of size n, where n is a positive integer less than or equal to 10. The elements in the matrix should be randomly generated integers ranging from -100 to 100. The code should also compute and print the sum of the main diagonal elements in the matrix. |
Here's an example implementation of the requested method:
```java
import java.util.HashMap;
import java.util.Map;
public class AlphabetCounter {
public static Map<Character, Integer> countAlphabets(String str) {
Map<Character, Integer> countMap = new HashMap<>();
str = str.toUpperCase();
... | Construct a java method to convert alphabets to uppercase and count the number of occurrences of each alphabet in the string.
String str = "This is a great day"
Requirements:
- The method should have a time complexity of O(n), where n is the length of the input string.
- The method should have a space complexity of O... |
Here is a Java code that finds the longest common prefix in a string array:
```java
public class LongestCommonPrefix {
public static String findLongestCommonPrefix(String[] arr) {
if (arr == null || arr.length == 0) {
return "";
}
String prefix = arr[0]; // Start with t... | Write a Java code to find the longest common prefix in a string array.
String [] arr = {"flower","flow","flight", "fleet"} |
Here is an example implementation of a switch-case statement in Java that meets the given requirements:
```java
public class SwitchCaseExample {
public static void main(String[] args) {
String input = "g";
switch (input) {
case "a":
System.out.println("Perform o... | 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 10 different cases.
- Each case should perform a ... |
Here is the code to create a two-dimensional array in Java with values corresponding to the given output:
```java
public class FibonacciArray {
public static void main(String[] args) {
int[][] fibonacciArray = new int[1][10];
fibonacciArray[0][0] = 0;
fibonacciArray[0][1] = 1;
for ... | Create a two-dimensional array in Java with values corresponding to the given output. Each element in the array should be the sum of the previous two elements in the Fibonacci sequence. The output should be: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. |
Here's the Java code snippet to calculate the area of a triangle given three points:
```java
public class TriangleAreaCalculator {
public static void main(String[] args) {
int x1 = 0, y1 = 0;
int x2 = 5, y2 = 0;
int x3 = 0, y3 = 5;
double area = calculateTriangleArea(x1, y1, x2, y2... | Write a Java code snippet to calculate the area of a triangle, given three points. The points should not be collinear.
x1, y1 = 0, 0
x2, y2 = 5, 0
x3, y3 = 0, 5
The code should handle the case when the points are collinear and output an appropriate message. |
Here is a Java program that counts the occurrences of a specific word in an array of sentences, while ignoring variations in capitalization:
```java
public class WordCount {
public static void main(String[] args) {
String[] sentences = {"I ate an apple", "I love apples", "I bought a banana", "Apples are de... | 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.
array = ["I ate an apple", "I love apples", "I bought a banana", "Apples are delicious"]... |
Here is the code to create an array, add elements, sort in ascending order, and print the elements in reverse order in Java:
```java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Create an array
int[] array = {5, 7, 3};
// Sort the array in ascen... | Create an array in Java and add the following elements: 5, 7, 3. Sort the array in ascending order and then print the elements in reverse order. |
To calculate the sum of all elements of an array without using any loop or recursion, you can use the `Arrays` class from the `java.util` package in Java. The `Arrays` class provides the `stream()` method, which allows you to convert an array into a stream. Then, you can use the `sum()` method of the `IntStream` class ... | Create an algorithm in Java to calculate the sum of all elements of an array. Your algorithm should not use any loop or recursion. |
Here's a program in Java that swaps two numbers without using a temporary variable:
```java
public class NumberSwapper {
public static void main(String[] args) {
int a = 5;
int b = 3;
System.out.println("Before swapping:");
System.out.println("a = " + a);
System.out.println... | Create a program in Java that takes in 2 numbers and swaps them. However, you are not allowed to use a temporary variable for the swap operation.
int a = 5;
int b = 3; |
To create a variable in Java for storing a user's first name with a minimum length of 3 characters and a maximum length of 20 characters, you can use the String data type and check the length of the user input using an if statement. Here's an example:
```java
import java.util.Scanner;
public class Main {
public s... | 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. |
Sure! Here's a Java code that prints the Fibonacci series till a given number without using recursion:
```java
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number: ");
... | Write a code in Java to print the Fibonacci series till a given number, where the input is a user-specified number. However, you should not use recursion to solve this problem. |
Sure! Here's a Java code to clone a linked list using iteration and then reverse the cloned linked list:
```java
class Node {
int data;
String str;
Node next;
Node(int data, String str) {
this.data = data;
this.str = str;
next = null;
}
}
class LinkedList {
Node head;
... | Write a Java code to clone a linked list using iteration. The original linked list contains nodes with both integer values and strings. Additionally, you should implement a method to reverse the cloned linked list. |
Here's a Java code that generates a Fibonacci sequence of n numbers, where n is provided as input by the user:
```java
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner input = new Scanner(System.in)... | Generate a Fibonacci sequence of n numbers, where n is provided as input by the user, using Java. |
Here is a Java program that takes a string as input, reverses the order of its characters, removes any duplicate characters, ignores punctuation or special characters, keeps track of the frequency of each character, and displays the characters in descending order of frequency:
```java
import java.util.*;
public class... | Write a Java program that takes in a string and reverses the order of its characters, while also removing any duplicate characters. The program should ignore any punctuation or special characters and should only consider alphanumeric characters. The program should also keep track of the frequency of each character and ... |
Here is a Java code that generates a Fibonacci number at a given index using recursion with a time complexity of O(2^n):
```java
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
... | 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(2^n). |
Here is a Java program that finds the first 10 prime numbers starting from 2:
```java
public class PrimeNumbers {
public static void main(String[] args) {
int count = 0;
int number = 2;
while (count < 10) {
if (isPrime(number)) {
System.out.println(number);
... | Write a Java program that finds the first 10 prime numbers, starting from 2.
Provide a piece of erroneous code that tries to find the first 5 prime numbers starting from 1 instead of 2. |
Here's an implementation of a basic calculator in Java that supports addition, subtraction, multiplication, and division operations. It also handles parentheses for grouping expressions and supports floating-point numbers. It includes a history feature that stores previous calculations and allows the user to retrieve t... | Implement a basic calculator in Java that can handle addition, subtraction, multiplication, and division operations. The calculator should also support parentheses for grouping expressions. The input expression can include both positive and negative numbers, and the calculator should be able to handle floating-point nu... |
Here's a Java program that solves the problem:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class SumOfThreeLargestDistinctValues {
public static void main(String[] args) {
int[] array = {3, 8, 4, 16, 1, 7, 7, 4, 8, 8};
// Convert the array to a ... | Create a Java program that takes an array of n elements (where n > 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:
[3, 8, 4, 16, 1, 7, 7, 4, 8, 8]
Expected output:
Sum of the three largest distinct val... |
The error in the initialization of the `fibonacci` array is that it is being initialized with a length of `range + 1`, but the Fibonacci sequence only requires `range` elements.
To fix the error, we need to change the line `int[] fibonacci = new int[range + 1];` to `int[] fibonacci = new int[range];`.
Corrected code... | Create a program in Java to print the Fibonacci number at the end of the given range.
Erroneous Code Reference:
```java
public class Fibonacci {
public static void main(String[] args) {
int range = 10;
int[] fibonacci = new int[range + 1];
fibonacci[0] = 0;
fibonacci[1] = 1;
... |
Here's a Java program that prints the nth number in the Fibonacci sequence without using recursion or an iterative loop:
```java
public class FibonacciWithoutRecursion {
public static void main(String[] args) {
int n = 10; // Specify the nth number you want to find
int first = 0;
int second... | Write a Java program to print the nth number in the Fibonacci sequence, but without using recursion or an iterative loop. |
Here is a Java program that performs the given task:
```java
import java.util.ArrayList;
import java.util.List;
public class SumOfOddNumbers {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
... | Generate a Java program to perform the following task.
Given a list of integers, find the sum of all the odd numbers in the list and print the result. |
Here is a Java class that validates if a given number is prime or not, and also provides a method to return all prime numbers within a given range:
```java
import java.util.ArrayList;
import java.util.List;
public class PrimeValidator {
public static boolean isPrime(int number) {
if (number <= 1) {
... | Generate a class in Java that validates if a given number is a prime or not. The number must be between 1 and 1,000,000. The class should also provide a method that returns all prime numbers within a given range, where the range must be between 1 and 10,000. The class should be able to handle large input numbers effici... |
Here is a Java code that searches for an element in a list and returns its index if it exists:
```java
import java.util.ArrayList;
import java.util.List;
public class ElementSearch {
public static int search(List<Integer> list, int target) {
if (list == null || list.isEmpty()) {
return -1;
... | Write Java code to search for the given element in the list and return its index if it exists. The list may contain duplicates and may not be sorted. |
Here is a Java code that generates 20 random numbers between -100 and 100, computes the sum and average, displays the highest and lowest numbers, and sorts the numbers in ascending order:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Ran... | Generate 20 random numbers between -100 and 100 using Java. Compute the sum of all the generated numbers and find the average. Display the highest and lowest numbers generated. Finally, sort the numbers in ascending order and display the sorted list. |
Here is a Java program that calculates the sum of the series 1^3+2^3+3^3+.....+n^3:
```java
import java.util.Scanner;
public class SumOfCubes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer (less than or equal to 100):... | 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. |
Here is an example of a Java program that demonstrates multiple inheritance using interfaces and abstract classes:
```java
// Interface 1
interface Interface1 {
void display();
}
// Interface 2
interface Interface2 {
void show();
}
// Abstract class
abstract class AbstractClass {
abstract void print();
}... | Implement a Java program that demonstrates the concept of multiple inheritance using interfaces and abstract classes. |
Here is the Java program that checks if a given number is divisible by both 3 and 5:
```java
import java.util.Scanner;
public class DivisibilityChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = s... | Write a program in Java that checks if a given number is divisible by both 3 and 5. If it is divisible by both, print "Divisible by both 3 and 5". If it is only divisible by 3, print "Divisible by 3". If it is only divisible by 5, print "Divisible by 5". If it is not divisible by either, print "Not divisible by 3 or 5"... |
Here is the Java class for car objects:
```java
public class Car {
private String make;
private String model;
private int yearOfManufacture;
private String color;
private int currentSpeed;
public Car(String make, String model, int yearOfManufacture) {
this.make = make;
this.mod... | 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, and year of manufacture.
2. Include private instance variables for the car's make, model, year of manufacture, color, and current speed.
3. Implement getter and setter... |
Sure! Here's a code snippet in Java that loops through an array and calculates the sum of all the elements:
```java
public class SumArrayElements {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
... | Generate a code in Java to loop through an array and calculate the sum of all the elements in the array. |
Here's a Java program that prints out the Fibonacci series within a given range (excluding numbers divisible by 3):
```java
public class FibonacciSeries {
public static void main(String[] args) {
int rangeStart = 5;
int rangeEnd = 15;
int firstNum = 0;
int secondNum = 1;
in... | Create a Java program that prints out the Fibonacci series within a given range, but exclude any numbers that are divisible by 3.
Range = (5, 15) |
Here's an example of a Person class in Java that stores a person's name, email, gender, age, and a list of their favorite hobbies:
```java
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private String email;
private String gender;
private int age;
pri... | Create a class Person in Java that stores a person's name, email, gender, age, and a list of their favorite hobbies. |
Here's the correct Java switch statement:
```java
boolean isWeekend = true;
boolean isWorking = false;
switch (isWeekend) {
case true:
System.out.println("Enjoy your weekend!");
break;
case false:
switch (isWorking) {
case true:
System.out.println("Keep up t... | Write a Java switch statement that prints different messages based on the following conditions:
1. If the boolean variable "isWeekend" is true, print "Enjoy your weekend!"
2. If the boolean variable "isWeekend" is false and the boolean variable "isWorking" is true, print "Keep up the good work!"
3. If both "isWeekend"... |
Here's a Java program that implements the logic described above:
```java
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
... | Write a Java program to read the following text and count the number of words in the given sentence. However, the program should ignore any words that are enclosed within quotation marks.
For example, if the input sentence is:
This is a "sample" sentence.
The program should count only the words "This", "is", "a", and... |
Here is the Java program that takes two integers as command line arguments and adds them together:
```java
public class AddIntegers {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Error: Please provide two integers as command line arguments.");
... | Write a Java program that takes in two integers as command line arguments and adds them together. The program should then print the sum. The program should handle cases where the inputs are not valid integers and should display an error message in such cases. |
Here's an example of a Java class that represents a point in 2D space:
```java
public class Point {
private int x;
private int y;
public Point(int x, int y) {
setX(x);
setY(y);
}
public int getX() {
return x;
}
public void setX(int x) {
if (x <... | 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 integers between -100 and 100, inclusive. Additionally, the class should have a method to calculate the distance between two points in 2D space. |
Here's an example of a multithreaded class in Java to submit a form, ensuring uniqueness and captcha verification for each submission:
```java
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
class FormSubmissionThread extends Thread {
private static Set<String> submittedForms = new HashSe... | Write a multithreaded class in Java to submit a form, ensuring that each form submission is unique and includes a captcha verification. |
Here is a Java program that prints the first 20 prime numbers from the Fibonacci series, where each number is less than 100:
```java
public class FibonacciPrime {
public static void main(String[] args) {
int count = 0; // count of prime Fibonacci numbers
int first = 0; // first Fibonacci number
... | Write a Java program to print the first 20 numbers in the Fibonacci series, where each number is a prime number and less than 100. |
Here is a Java program that prints all possible combinations of binary numbers of length 4:
```java
public class BinaryCombinations {
public static void main(String[] args) {
int length = 4;
int[] binary = new int[length];
printCombinations(binary, 0);
}
public static void printCo... | Write a Java program to print all possible combinations of binary numbers of length 4. |
Here's a Java program that solves the given problem:
```java
import java.util.ArrayList;
import java.util.List;
public class MaxNumberFinder {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(-2);
numbers.add(10);
... | Create a Java program to find the maximum number within a list of integers, excluding any negative numbers. Additionally, the program should handle the case where the list is empty and return an appropriate message. |
Here is an example Java program that meets the given requirements:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CircleCalculator {
private static final double PI = 3.14159265359;
private static Map<Double, Double> cache = new HashMap<>();
public static vo... | Create a Java program to find the area and circumference of a circle with a given radius. The program should be able to handle multiple circles with different radii in a single run.
Additionally, the program should allow the user to choose between calculating the area and circumference for each circle. The program sho... |
Sure! Here's an example of Java code that creates an ArrayList of integers and sorts it in ascending order using the `Collections.sort()` method:
```java
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of integer... | Write a Java code to create an arraylist of integers and sort it in ascending order. |
Here is the code in Java to generate a random number between 12 and 23, ensuring that the generated number is divisible by 3 and does not contain the digit 4:
```java
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
... | Write code in Java to generate a random number between 12 and 23, ensuring that the generated number is divisible by 3 and does not contain the digit 4. |
Here is the corrected code:
```java
public static int[] getFirstNPrimeNumbers(int n) {
int[] primeNumbers = new int[n];
int count = 0;
int number = 2;
while (count < n) {
if (isPrime(number)) {
primeNumbers[count] = number;
count++;
}
number++;
}... | Write a method in Java that returns an array of the first N prime numbers. n=10
**Reference Erroneous Code:**
```java
public static int[] getFirstNPrimeNumbers(int n) {
int[] primeNumbers = new int[n];
int count = 0;
for (int i = 2; count < n; i++) {
if (isPrime(i)) {
primeNumbers[count... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.