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;
}
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.
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.
I want to display every number leading up to the variable 'number'.
Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
System.out.println(recursion(number));
}
public static int recursion(int number)
{
for (int i=0;i>number;i++)
{
return recursion(i);
}
else {
return number ;
}
}
}
You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.
Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:
void myRecursiveProgram(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
System.out.println(n); // Complete the task by printing the last number
}
Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:
void printNumbersUpToN(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1);
System.out.println(n);
}
Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.
Your code doesn't compile, you have an else without if.
What you are trying to do is something like:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
recursion(number);
}
public static void recursion(int number)
{
if (number>1)
{
recursion(number-1);
System.out.print(number);
}
else {
System.out.print(number);
}
}
}
This short code will also print the numbers right.
public void recursion(int number){
if (number>1)
recursion(number-1);
System.out.println(number);
}
Why This code is not giving compile time error
package com.test;
public class Recursive {
public static int name(int number) {
if (number <= 0)
return 0;
return 1 + name(number / 10);
}
public static void main(String[] args) {
System.err.println(name(124));
}
}
Because you did not write the brackets. Each loop, if or else can be followed by a block of code ({...}) or a single statement. So your code is equivalent to:
package com.test;
public class Recursive {
public static int name(int number) {
if (number <= 0) {
return 0;
}
return 1 + name(number / 10);
}
public static void main(String[] args) {
System.err.println(name(124));
}
}
Your code is equivalent to
if (n <0) {
return 0;
}
return 1 + name (n/10);
This completely legal code
The reason there is no compile time error is because your code is syntactically correct. If the code is not doing what you expected, please explain how.
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}