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.
Related
i recently learned the use of public, private and double in my different classes. But for some reason i cant understand why this is not working. My intention was to use three different classes as an exercise: I want Do() to make numbers from 0 to 20 and show only the numbers 0 till 10 on my console using the method for1() in a different class. Can someone please fix this issue? I dont need a shorter code or a code in just 1 class since i need it to educate myself using many classes. I would thank anyone if you could fix this issue using this kind of setup. Thanks in advance.
public class MainM {
public static void main(String[] args) {
loop Q = new loop();
Q.Do();
}
}
//------------------------------------------------------
public class loop {
public double b;
Sum R = new Sum(); // Java shows the problem is here : at Sum.<init>(Sum.java:3)
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1();
}
}
}
}
//--------------------------------------------------
public class Sum {
loop Q = new loop();
public void for1() {
System.out.println("b " + Q.b);
}
}
You can have your Sum class only with the print statement and the method for1() should have one parameter. Bellow is my suggestion
public class Sum {
public void for1(double b) {
System.out.println("b " + b);
}
}
And your loop class will be
public class loop {
public double b;
Sum R = new Sum();
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1(b);
}
}
}
}
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num<=2){
rec(++num);
}
System.out.println(num);
}
}
but I want to do this with the following way.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num==2){
return;
}
rec(++num);
System.out.println(num);
}
}
Expected output:
2,1,0
but it shows:
2,1
Why does it happen?
++num increments num, which (as here) makes the code harder to understand.
Try calling rec(num + 1); instead.
You may find your terminating condition needs to be modified to:
if (num > 2)
Terminating conditions are usually the “do nothing” case, which is the case here.
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.
rec(0) prints rec(1),1
rec(1) prints rec(2),2
rec(2) prints nothing
Total output: 2,1
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.
Your if statement is also backwards.
public class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num) {
if (num < 2) {
rec(num + 1);
}
System.out.println(num);
}
class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num <= 2){
rec(num + 1);
} else return;
System.out.println(num);
}
}
++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.
When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.
what is the reason that i am getting java.lang.stackoverflowerror after running this code?
class recursion {
public static int func(int n) {
int result;
result = func (n - 1);
return result;
}
}
class Output {
public static void main(String args[]) {
recursion obj = new recursion();
System.out.print(obj.func(12));
}
}
You have no stopping condition.
You always call func (n - 1), and therefore get an infinite chain of recursive calls until the stack overflows.
A proper recursive method must have a stopping condition. For example, the stopping condition may be when n reaches 0 :
public static int func (int n) {
if (n <= 0)
return 1;
int result = func (n - 1);
return result;
}
When is the method func stopping?
You are calling it with 12 and then is going back to an infinite recursion.
On an unrelated note: you should take a look at the Java code conventions
This is because there is no limit (end point) for the recursive function call.
Try this -
class recursion
{
public static int func (int n)
{
int result = 0;
if(n > 0)
result = func (n - 1);
return result;
}
}
class Output
{
public static void main(String args[])
{
System.out.print(recursion.func(12));
}
}
You should call static function with class name.
I'm a first year programmer and not completely certain on what I'm doing wrong with this code. Please, can anyone help?
package ________;
public class _______
{
public static void main(String[] args)
{
public int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
}
This line displays an illegal start of expression method every time I attempt to compile or run the program:
public int getFactorial(int number)
The ____'s just represent the hidden package and class names. Using NetBeans IDE 7.4, Java apllication
You cannot have other methods or functions inside the main function. You can however call the functions from your main function.
Please write the code as
public static void main(String[] args)
{
int number = 10;
/* if you want user to input */
Scanner get = new Scanner(System.in);
number = get.nextInt(); // get the next integer user types :)
getFactorial(number);
}
public static int getFactorial(int number)
{
int factor = 1;
if (number == 1)
{
System.out.println("Returned 1");
}
else
{
factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
}
return factor;
}
This way, your function would be inside the same Class but outside the bounds of Main method. In the main method, you would be calling it and where the control would be transfering to the getFactorial function.
You have a method (getFactorial) inside another (main). They need to come one after another.
public static void main(String[] args){
getFactorial(int number);
}
public static int getFactorial(int number)
{
if (number == 1)
{
System.out.println("Returned 1");
return 1;
}
else
{
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
You can't write a method inside another method. Your code should look like this:
package ________;
public class _______ {
public static void main(String[] args) {
//call getFactorial, for example
int result = getFactorial(2);
}
public static int getFactorial(int number) {
if (number == 1) {
System.out.println("Returned 1");
return 1;
} else {
int factor = number * getFactorial(number - 1);
System.out.println("Returned " + factor);
return factor;
}
}
}
I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)