I’m a bit of a noob at Java programming, and I have been scratching my head at this for the past hour. The code for this program compiles just fine; I just need to figure out how to make the variable "result" from the method "maxMod5" display at the end.
This is the version of the code that compiles without error.
import java.util.Scanner;
public class MaxMod {
public static int maxMod5(Scanner input) {
System.out.println("Enter two integers");
int result;
int a = input.nextInt();
int b = input.nextInt();
if (a == b)
result = 0;
else if (a % 5 == 0 && b % 5 == 0) {
if (a > b)
result = b;
else
result = a;
}
else if (a > b)
result = a;
else
result = b;
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Here we go");
maxMod5(input);
}
}
I’m certain the solution is very simple, but I can’t seem to get it to work by simply putting
System.out.println(result);
If I write that command in the main method the compiler says it doesn’t recognize the variable; if I write it in "maxMod5" it gives another error.
Thanks in advance!
>Solution :
Something that would work better in your case would be to print the returned value of your method maxMod5. The reason for this is that your result value is only accessible in the specific method (maxMod5), which is why you are not able to print it in your main method, since it cannot be accessed.
Something like this at the end of your main method would work:
System.out.println(maxMod5(input));
By directly printing your method returning the wanted value, you can effectively get the same result that you want with printing the result value directly.
You could also use a new variable to get the value returned by your method, and then print that variable instead.