简体   繁体   中英

JAVA. Running a function from different class

I am new on Java and I need a small help.

Why when I run a function from another class it doesn't work(obj.setTime()):

public class Main {
public static void main(String[] args) {
    apple obj= new apple();
    System.out.println(obj.TheTime());
    obj.setTime();
    System.out.println(obj.TheTime());
}}  

it also doesn't work if I put obj.setTime(h,m,s); or obj.setTime(int h, int m, int s); but if I put obj.setTime(1,2,3); it works. I am addint setTime() function.

public void setTime(int h, int m, int s) {
    Scanner reader= new Scanner(System.in); 
    h=reader.nextInt();
    m=reader.nextInt();
    s=reader.nextInt();
    hour= ((h>=0 && h<24) ? h: 0);
    minute= ((m>=0 && m<60) ? m: 0);
    second= ((s>=0 && s<60) ? s : 0);   
}

You've specified three parameters to your setTime() method of type int in your method definition, so you need to specify three parameters of type int when you call your method.

So to take your non-working examples:

obj.setTime(); - won't compile, as you're not providing any parameters.

obj.setTime(h,m,s); - won't compile, as you're providing it three variables that don't exist.

obj.setTime(int h, int m, int s) - won't compile, as you're confusing the definition of the function with calling it.

Your only working example ( obj.setTime(1,2,3); ) passes three integers - 1, 2 and 3 - hence it compiles.

Note though that your setTime() method doesn't actually use any of the parameter values passed in - it immediately overwrites them with values read from the console. So it may be that you want something like:

public void setTime() {
    Scanner reader= new Scanner(System.in); 
    int h=reader.nextInt();
    int m=reader.nextInt();
    int s=reader.nextInt();
    hour= ((h>=0 && h<24) ? h: 0);
    minute= ((m>=0 && m<60) ? m: 0);
    second= ((s>=0 && s<60) ? s : 0);   
}

...which doesn't take any parameters (so you can just call setTime() ), but instead defines the variables read from the console within the method body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM