开发者

How do I use parameters correctly in Java and why are they advantageous?

开发者 https://www.devze.com 2022-12-22 06:48 出处:网络
Here is the code: class Time { public static void printTime (int hour, int minute) { System.out.print (hour) ;

Here is the code:

class Time {
public static void printTime (int hour, int minute) {
System.out.print (hour) ;
System.out.print (":") ;
System.out.print (minute) ; 
} 

public static void main (String[] args) {
hour = 11 ; 
minute = 30 ;
printTime () ; 

}
}

Here is what terminal says when I try to compile it:

david-allenders-macbook-pro:~ davidallender$ Javac Time.java
Time.java:9: cannot find symbol
symbol  : variable hour
location: class Time
hour = 11 ; 
^
Time.java:10: cannot find symbol
symbol  : variable minute
location: class Time
minute = 30 ;
^
Time.java:11: printTime(int,int) in Time cannot be applied to ()
printTime () ; 
^
3 errors
david-allenders-macbook-pro:~ davidallender$ 

I'm in the process of learning so I don't really know what's going on. Right now I'm in the section in the book about parameters 开发者_运维问答in/on/within/above/preposition (I'm not sure what the right preposition is) methods.

  • What does a parameter do?
  • Why is it useful?
  • What did I do wrong in the above code?
  • What did the error message mean?


Parameters give a method information it needs to do its job. For example, a function to find the square root of a number would have that number as a parameter.

You need to pass arguments to give the parameters values. So instead of trying to set minute and hour in the main method, you need to call

printTime(11, 30);

As a sort of meta-comment, this is the kind of thing you tend to learn pretty early - and while sites like this can help you with specific questions, you'd be better off reading a good entry level book about Java. If you're already reading a book but it didn't describe parameters clearly, you might want to think about getting another book :)


This should be better:

class Time {
public static void printTime (int hour, int minute) {
System.out.print (hour) ;
System.out.print (":") ;
System.out.print (minute) ; 
} 

public static void main (String[] args) {
int hour = 11 ; 
int minute = 30 ;
Time.printTime (hour, minute) ; 

}
}

Awful formatting. Do yourself a favor and think more carefully about how you format your code. It doesn't matter much for a small example like this, but you'll need it if your ambitions and programs grow.

I might write it like this:

package cruft;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Time
{
    private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("00");
    private static final int DEFAULT_CAPACITY = 8;
    private static final char DEFAULT_DELIMITER = ':';

    private final int hour;
    private final int minute;
    private final int second;

    public Time()
    {
        this(0, 0, 0);
    }

    public Time(int hour)
    {
        this(hour, 0, 0);
    }

    public Time(int hour, int minute)
    {
        this(hour, minute, 0);
    }

    public Time(int hour, int minute, int second)
    {
        this.hour = hour;
        this.minute = minute;
        this.second = second;
    }

    public String toString()
    {
        StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);

        builder.append(DEFAULT_FORMAT.format(hour))
               .append(DEFAULT_DELIMITER)
               .append(DEFAULT_FORMAT.format(minute))
               .append(DEFAULT_DELIMITER)
               .append(DEFAULT_FORMAT.format(second));

        return builder.toString();
    }

    public static void main(String[] args)
    {
        Time time = new Time(11, 5);
        System.out.println(time);
    }
}

Note: Consistent brace placement, methods indented, etc. That's what I mean.


I think one major thing you're doing wrong and should be pointed out specifically is that you're declaring parameters without defining their types. Java is known for it's static-as-a-frozen-rock type system which means that you always have to define the type of the variable, no matter what. To compare, in PHP you can do $number = 1; while in Java you cannot.

As a prototype, each variable/parameter declaration follows the [type] [name] = [possible default value]; pattern, for example int number = 1;. Valid types are primitives (int, double, byte, char etc.) and of course objects such as String or Calendar or whatever class you might be using.

The same staticness applies to calling methods, you need to explicitly provide each method with exact amount of parameters with correct types to be able to call them. Java does automatically cast down or up some primitive values such as int to long where applicable, but generally in Java you're going to use actual objects and those are only downcasted if applicable. You can't provide default values for methods' parameters automatically in the same way as C/C++/PHP, that is you can't do this

public void callMe(int number = 911) { ... }

but you have to do this

public void callMe() { callMe(911); }
public void callMe(int number) { ... }

to get the same effect.

Naturally there's always exceptions to even the most fundamental rules such as difference between static and dynamic typing, satisfying method with right amount of parameters and default values but you can forget those for the time being and concentrate on the basics first. Hopefully this helps you!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号