I have been scouring this site and others for the last two days, and thus am aware of the overwhelming amount of preexisting questions similar to this one. However, having only started programming three or four weeks ago, I am unable to make sense of any of them and their threads. Considering this, I have an issue that to the more experienced likely possesses a painfully basic and straightforward solution.
Using Eclipse, I must create a program which does the following:
The code I have created (displayed below) successfully reads in the user input, but fails to print out both the larger integer and the larger integer's last digit. It instead prints out "0". This is what is printed out to the console:
Enter First Integer: (Entered Integer)
Enter Second Integer: (Entered Integer)
Larger Integer: 0
Last Digit: 0
I believe that the code should function correctly, save for the fact that values determined inside the methods are not being returned to the main. No error messages are being displayed by Eclipse, which leads me to believe that the issue lies within my return statements. Any suggestions or solutions are welcomed and desired. Thank you.
import java.util.Scanner;
public class thursdayWork{
//Determines larger integer and returns it.
public static int processAndReturn(int int1, int int2, int answer){
answer = Math.max(int1, int2);
return answer;
}
//Determines last digit of integer and returns it.
public static int processLargerInt(int answer, int lastDigit){
if((answer >= 0) && (answer < 10))lastDigit = (answer % 10);
else if((answer >= 10) && (answer < 100))lastDigit = (answer % 100);
else if((answer >= 100) && (answer < 1000))lastDigit = (answer % 1000);
else if((answer >= 1000) && (answer < 10000))lastDigit = (answer % 10000);
else System.out.print("Pick smaller numbers.");
return lastDigit;
}
//Calls methods and prints returned values.
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int int1;
int int2;
int answer = 0;
int lastDigit = 0;
System.out.print("Enter First Integer: ");
int1 = console.nextInt();
System.out.print("Enter Second Integer: ");
int2 = console.nextInt();
processAndReturn(int1, int2, answer);
System.out.println("Larger Integer: " + answer);
processLargerInt(answer, lastDigit);
System.out.print("Last Digit: " + lastDigit);
}
}
Instead of passing the answer as a param to both the methods, you should have it returned from the method. You should read more about pass by value vs pass by reference.
public static void main(String[] args) {
// Your scanner code here.
int answer = processAndReturn(int1, int2);
System.out.println("Larger Integer: " + answer);
int lastDigit = processLargerInt(answer);
System.out.print("Last Digit: " + lastDigit);
}
public static int processAndReturn(int int1, int int2){
return Math.max(int1, int2);
}
public static int processLargerInt(int answer) {
return answer % 10;
}