Issue
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
I recommend checking out information on variable scope in Java.
You have two main options:
- Save the result of
maxMod5(input)
to a variable and then print out the variable. - Print out the result of
maxMod5(input)
directly.
The following will result in an error because result
is declared in maxMod5 as a local variable and is outside the scope of the main method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Here we go");
maxMod5(input);
System.out.println(result); // variable result not in scope
}
The following will result in an error because it simply references a method name but does not call the method.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Here we go");
maxMod5(input);
System.out.println(maxMod5); // method name, not invocation
}
Solutions to your issue:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Here we go");
// option 1
int x = maxMod5(input);
System.out.println(x);
// option 2
System.out.println(maxMod5(input));
}
Answered By - John Stone
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.