Calling Private Methods
Calling a private method from a public one is exactly the same as calling any other method:
public void doStuff() {
System.out.println("Stuff done.");
}
private void doOtherStuff() {
System.out.println("Other stuff done.");
}
public void showHowItWorks() {
doStuff();
doOtherStuff();
// or if you prefer this style:
this.doStuff();
this.doOtherStuff();
}
The important difference is that you can only call private methods from inside the class where they were defined:
class PublicExample {
public static void doStuff() {
System.out.println("Stuff done.");
}
}
class PrivateExample {
private static void doStuff() {
System.out.println("Stuff done.");
}
}
class Example {
public static void Main(String[] args) {
PublicExample.doStuff(); // Works
PrivateExample.doStuff(); // Doesn't work (because it's private and defined in a different class)
}
}
Return Values
private void isValid(int hour, int minute) {
if (hour >= 0 && hour <=23) {
System.out.println("Hour is valid");
hourIsValid = true;
} else {
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
The problem with this approach is that your program immediately dies if you input a bad hour or minute. What if I want to loop until I get a good input?
I think the main problem is that you don't know how to return a value from a method. Here's an example of a function that always returns true
:
public static boolean trueExample() {
return true;
}
public static void main(String[] args) {
boolean returnValue = trueExample();
System.out.println("trueExample() returned " + returnValue);
}
You can also make it more complicated:
/**
* @return the input value minus one.
*/
public static int oneLess(int num) {
return num - 1;
}
public static void main(String[] args) {
int num = 10;
// Print 10
System.out.println(num);
// Print 9
num = oneLess(num);
System.out.println(num);
// Print 8
num = oneLess(num);
System.out.println(num);
}
Here's one that will return true
if num
is in the range 10-20 and false
otherwise:
public boolean isValid(int num) {
return num >= 10 && num <= 20;
}
This version does exactly the same thing, but you may find it easier to read since it's more explicit:
public boolean isValid(int num) {
/* Numbers less than 10 are invalid */
if(num < 10) {
return false;
}
/* Numbers greater than 20 are invalid */
else if (num > 20) {
return false;
}
/* By process of elimination, everything else is valid */
else {
return true;
}
}
Let me know if that's not enough to help you with your problem.