Kutam
Kutam

Reputation: 85

Printing an Integer and their half calling it from main method

Im only started learning java. Im practicing on how to print and half integer

I have define the main method and for the halfing method I have also define it in the same class but it wont compile. Any suggestions? this is my code

public class IntAndHalf {

    public static void main(String[] args) {
        double y;
        for (int i = 1; i <= 20; i++) {
            System.out.println(i + " " + y);
        }
    }
    public static double halfOfint(int i){
        for (i = 0; i <= 20; i++){
            y = i/2;
            return (y);
        }
    }
}

Upvotes: 0

Views: 356

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59978

Hint

You have a lot of problem in your code :

  • y is not define in your main method
  • The i is already declared in your method, so you have not to declare it again in your loop (int i = 0;) just use it (i = 0;).
  • Your miss ; in the end of y = (i/2)
  • When you make ; in the end of your loop, the next block will not executed for(int i = 1; i <= 20; i++ );
  • You have to return(y) in the end of your method not in your loop

Correct this typos and your code will compiled, another thing you never call your method HalfOfInt so don't wait to get information from this method, you have to call in your main method.


Edit

Your code in this case should look like this:

public static void main(String[] args) {
    for (int i = 1; i <= 20; i++) {
        System.out.println(i + "-" + HalfOfInt(i));
        //                              ^-----------call your method which
                                                  //take an int and return the (i/2)
        //                 ^-------------------------Print your value
    }
}

public static double HalfOfInt(int i) {
    return (double) i / 2;//<<----------- no need to use a loop just return (i/2)
}

Upvotes: 1

dumbPotato21
dumbPotato21

Reputation: 5695

Multiple Problems :

  1. There is a ; after your for loop.
  2. y is not defined in your main method.
  3. You are missing a ; after y = (i/2)
  4. You never call HalfOfInt
  5. You declare i twice.

Also, you should stick with Java naming conventions. Methods should begin with a lower-case letter.

Upvotes: 0

Related Questions