Hi Im still new to java and Im having trouble working out passing values between methods. I still carnt get it right with all the researh I’ve done. Anyhow any comments or advice will be welcome.
To save you reading though the code bellow I have two methods that return a value and I the pass them into showTime(). however with the current format I only get zero’s.
Any advice apart from give up now.
import java.util.Scanner;
public class First
{
static int sH, sM;
public static void main(String args[]){
getHour();
getMinute();
showTime(sH,sM);
}
static int getHour(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the hour: ");
int setHour = input.nextInt();
if(setHour <= 24){
System.out.println("You entered " +setHour+ " for the hour.");
}else{
System.out.println("Please enter the hour number from 0 to 24");
getHour();
}
return sH;
}
static int getMinute(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the mintues: ");
int setMinute = input.nextInt();
if(setMinute <= 60){
System.out.println("You entered " +setMinute+ " for the minutes.");
}else{
System.out.println("Please enter the hour number from 0 to 60");
getMinute();
}
return sM;
}
private static void showTime(int sH, int sM){
System.out.println(+sH+":"+sM);
}
}
You are not saving your values in
sHorsMin your methods, and you are returning them. So, the values returned will be0 only.this should be: –
Also, you actually don’t need to return them, if you have declared them as static variables outside your main method.
A better idea is not to use
static variables. Declare yoursHandsMvariables inside yourmain method, as local variables.Now when you return the values from
getHour(), you can assign them to the local variables. And then work with them.So, your
mainmethod can be modified to: –And in
getHour(), change yourreturn sH;toreturn setHour;. Similarly ingetMinute()method.And in the else part, change
getHour()invocation toreturn getHour();