import java.util.Arrays;
import java.util.*;
import java.util.stream.Collectors;
// double the first even number greater than 3
public class FirstDouble {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,5,6,7,8,9);
/* int result = 0;
for(int e : numbers)
{
if(e>3 && e%2==0)
{
result = e*2;
break;
}
}
System.out.println(result);
*/
System.out.println(
numbers.stream()
.filter(Sample::isGT3)
.filter(Sample::isEven)
.map(Sample::doubleIt)
.findFirst());
}
public boolean isGt3(int number) {
return number > 3;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
public int doubleIt(int number) {
return number * 2;
}
}
Three modifications are needed to make the code compile:
Rename Sample to FirstDouble in order to properly reference the class
Rename the method isGt3 to isGT3
As the methods are referenced statically, add the static modifier to isGT3, isEven and doubleIt
After that, it prints out Optional[12]. If only the number should be printed, add a get after findFirst.
Related
i just made a problem which should return if a number "isHappy" or not. A number is happy if it meets some criteria:
A happy number is a number defined by the following process:
-Starting with any positive integer, replace the number by the sum of the squares of its digits.
-Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
-Those numbers for which this process ends in 1 are happy.
`
import java.util.HashSet;
import java.util.Set;
class Solution{
public int getNext(int n){
int totalSum = 0;
while(n > 0){
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n){
Set<Integer> seen = new HashSet<>();
while( n!=1 && !seen.contains(n)){
seen.add(n);
n = getNext(n);
}
return n==1;
}
}
class Main {
public static void main(String[] args){
isHappy(23); //this doesnt work.
}
}
`
I don't know how to call this function, tried different methods like int number = 23 for ex and then isHappy(number) sout(isHappy(number)); , number.isHappy() although this makes no sense, intellij is telling me to make a method inside main but i dont think i must do this, think there s another way.
There are a couple of problems here. When you run a Java application it looks for the main method in the class you run. Your class has no main method, instead it has an inner class that has a main method.
class Solution {
// existing methods
// no 'Main' class wrapping method
public static void main(String[] argv) {
}
}
The second problem is that main is a 'static' method but isHappy is an 'instance' method. To call it you need an instance of the class
// inside the `main` function
var sol = new Solution();
if (sol.isHappy(23)) {
System.out.println("23 is happy");
} else {
System.out.println("23 is not happy");
}
You have completely solved the problem. You only have to decide what to do with the result of your calculations. You can simply print a string depending on the result.
Please note, that the methods in your Solution class are not static. So, you need to create an instance of the class and call the methods on that instance.
import java.util.HashSet;
import java.util.Set;
class Solution {
public int sumOfDigitsSquares(int n) {
int totalSum = 0;
while (n > 0) {
int last = n % 10;
n = n / 10;
totalSum += last * last;
}
return totalSum;
}
public boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
n = sumOfDigitsSquares(n);
}
return n == 1;
}
}
class Main {
public static void main(String[] args) {
var solution = new Solution();
String answer = solution.isHappy(23) ? "Is happy" : "Not happy at all";
System.out.println(answer);
}
}
Here is one possible way to check all numbers from 1 to 100 for happiness and print the result for each number.
IntStream.rangeClosed(1, 100)
.mapToObj(i -> "" + i + " " + (solution.isHappy(i) ? "is happy" : "not happy"))
.forEach(System.out::println);
To call non-static methods of a class, you need an instance:
public static void main (String [] args) {
Solution foo = new Solution ();
boolean bar = foo.isHappy (49);
// do something with bar
}
To use a static method, you don't use an instance:
class Solution{
public static int getNext(int n){ ... etc ...
}
public static boolean isHappy(int n){ ... etc ...
}
public static void main (String [] args) {
boolean foo = isHappy (1024);
// do something with foo
}
Another problem is you are throwing away the result of isHappy (23).
System.out.println (isHappy(23));
System.out.println ("is 23 happy?" + (isHappy(23) ? "Yes" : "No");
are two possibilities.
i can't call a method with variable that is declared in a code block. (like in my case a if statement in a for loop)
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int input;
System.out.println("Enter 5 integers");
for (int i = 0; i <= 4; i++) {
input = scanner.nextInt();
arrayList.add(input);
}
isSorted(arrayList);
}
public static void isSorted(ArrayList<Integer> arrayList) {
boolean sorted;
boolean dSorted;
for (int i=0; i<=3; i++) {
if (arrayList.get((i+1)) > arrayList.get(i)) {
sorted = true;
} else if (arrayList.get((i+1)) < arrayList.get(i)) {
dSorted = true;
} else {
sorted = false;
}
}
printResult(sorted, dSorted);
}
public static void printResult(boolean sorted, boolean dSorted) {
if(sorted) {
System.out.println("This set of numbers is sorted in ascending order.");
} else if(dSorted) {
System.out.println("This set of numbers is sorted in descending order.");
} else {
System.out.println("This set of numbers is not sorted at all.");
}
}
}
compile error:
something like error:(33,21) java: variable sorted might not have been intialized
you should just initialize variable : sorted and dsorted
The problem is, that you can not guarantee that both variables are getting initialized in the loop. It depends on the list that is passed to the method.
Therefore you have to initialize those variables (probably false).
Consider the following in a ArrayList or LinkedList:
[Gloucestershire, Hampshire, Yorkshire, Lancashire]
shire is the longest common suffix of length 5.
The output should be 5
How can I write a method to achieve the above and return length
Try this.
Explanation is in the comments
package javaapplication1;
public class SegmentTree {
public static void main(String[] args) {
String[] array = {"Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"};
int i,j;
int min=10000000;
//reversing the strings and finding the length of smallest string
for(i=0;i<(array.length);i++)
{
if(array[i].length()<min)
min=array[i].length();
StringBuilder input1 = new StringBuilder();
input1.append(array[i]);
array[i] = input1.reverse().toString();
}
//finding the length of longest suffix
for(i=0;i<min;i++)
{
for(j=1;j<(array.length);j++)
{
if(array[j].charAt(i)!=array[j-1].charAt(i))
{
break;
}
}
if(j!=array.length)
break;
}
System.out.println(i);
}
}
What I am doing here is,first checking the last elem of all strings, then 2nd last and so on.
Time Complexity: O(n*m), n=number of strings, m=length of smallest string
Guava has a helper function called Strings.commonSuffix(CharSequence a, CharSequence b) that could be used in your algorithm. I know adding dependency like Guava only to have this function can be overkill - in this case you can take a look at the source code to see how this function is implemented and you can move this implementation to your program. Then your program could look like this:
import com.google.common.base.Strings;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CommonSuffixLengthMain {
public static void main(String[] args) throws IOException {
assert 5 == commonSuffixLength(Arrays.asList("Gloucestershire", "Hampshire", "Yorkshire", "Lancashire"));
assert 2 == commonSuffixLength(Arrays.asList("abc", "dbc", "qebc", "webc"));
assert 0 == commonSuffixLength(Collections.emptyList());
assert 0 == commonSuffixLength(Collections.singletonList("abc"));
assert 0 == commonSuffixLength(Arrays.asList("abc", "def", "zxc"));
}
private static int commonSuffixLength(final List<String> strings) {
int result = 0;
if (strings == null || strings.size() < 2) {
return result;
}
for (int i = 0; i < strings.size() - 1; i++) {
String prefix = Strings.commonSuffix(strings.get(i), strings.get(i + 1));
result = result == 0 ?
prefix.length() :
Math.min(prefix.length(), result);
}
return result;
}
}
The task is to find the prime number at a given number. Here is the code
import java.util.ArrayList;
public class Queue {
private static int number = 0;
private static int prime;
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
{
number++;
}
}
System.out.println(number );
}
public static void main(String args[]) {
calculatePrime(10001);
}
}
when the input value is 3 it prints out the correct value of 5 but when the input value is 10001 it prints out a number other than 104743
Here's your calculatePrime method as the compiler sees it:
public static void calculatePrime(int p) {
while (prime <p) {
if (number % 2 != 0)
number++;
prime++;
number++;
}
System.out.println(number );
}
You could use something like this:
public static void calculatePrime(int p) {
int primeCandidate = p;
while (!isPrime(primeCandidate)) {
primeCandidate++;
}
System.out.println(number );
}
And you'll need a method to return true if the candidate is a prime. There are loads of these available for the small price of a google search.
This bit of code I'm doing was for practice with "While loops". When I run this code to count the amount of digits in a number, java doesn't output anything, which I found odd because usually when I get something wrong it'd give me an error, but this one ran without error. Is someone able to point out and explain why no output is showing?
import static java.lang.System.*;
public class DigitCounter
{
public static int countDigits( int number )
{
int sum=0;
while(number>0);
{
sum++;
number = number/10;
}
return sum;
}
}
\\new class
import static java.lang.System.*;
public class DigitCounterRunner
{
public static void main( String args[] )
{
out.println(DigitCounter.countDigits(234));
}
}
You must delete ; after while(number>0); in your countDigits( int number ) method because it's block there.
You should have the body of countDigits( int number ) method like that:
public static int countDigits( int number )
{
int sum=0;
while(number>0)
{
sum++;
number = number/10;
}
return sum;
}