Home > database >  new to java...simple java method issue
new to java...simple java method issue

Time:01-13

I know the answer is relatively easy but ive spent forever trying to figure it out and I dont have much more time to waste. Im new to java so bear with me...

the problem im given is to create a method called doubleMe that takes in one integer paramenter, val, doubles the value of val and returns the result. Print out the value of both the input and the output after calling the method doubleMe so that it prints like this example:

Value : 2 Double: 4

this below is the code i have now...which is wrong and doesnt work but not sure where to go from here. Its gotta be an easy fix i cant be too far off. please help. thanks!

public static void main(String[] args) {
    doubleMe();
    
    System.out.println("Value: "   val);
    System.out.println("Doubled: "   result);
}
    
    public static int doubleMe(int val) {
        if (val != 0) {
            int result = val * 2;
        }
    return result;

    
    }

}

CodePudding user response:

It doesn't work because you initialize int result inside an if scope. Doing this

if (val != 0) {
  int result = val * 2;
}

means that result is living only between those { }. In order to make it work, make sure to initialize it outside of the scope, for example:

int result = 0;
if (val != 0) {
  result = val * 2;
}

Or you can do

if (val != 0) {
  int result = val * 2;
  return result;
}
return 0; // meaning the val is 0

this will return the result only if if clause is hit, if not it will return 0. You're missing the val and result in the main() method as well. Summed up, you can do

public static void main(String[] args) {
    int val = 2;
    int result = doubleMe(val);
    
    System.out.println("Value: "   val);
    System.out.println("Doubled: "   result);
}

public static int doubleMe(int val) {
  int result = 0;
  if (val != 0) {
    result = val * 2;
  }
  return result;
}

or

public static void main(String[] args) {
    int val = 2;
    int result = doubleMe(val);
    
    System.out.println("Value: "   val);
    System.out.println("Doubled: "   result);
}

public static int doubleMe(int val) {
  if (val != 0) {
    int result = val * 2;
    return result;
  }
  return 0;
}

CodePudding user response:

Here is the code.

    public static void main(String[] args) {
        int val = 2;

        System.out.println("Value: "   val);
        int result = doubleMe(2);
        System.out.println("Doubled: "   result);
    }

    public static int doubleMe(int val) {
        /*int result = 0;
        if (val != 0) {
            result = val * 2;
        }*/
        //Instead of above code you can use Ternary operator to return the value.
        return val != 0 ? val * 2 : 0;
    }
  •  Tags:  
  • Related