Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2011
    Posts
    2
    Rep Power
    0

    Default Need help with methods and 'for' loops?

    The method evenSquares takes a single int parameter, n, (for example, 10000), and then prints all of the (positive) even perfect squares less than n, each on a separate line. Notice that evenSquares has a void return type, since all it does is print integers to the console. Be sure to use the println method to print each entry of your output.

    Example: if n = 40, your code should print
    4
    16
    36

    (Hint: your method should be built around a for loop with a test component that asks if the square of the control variable (say, k) is < n. Thus, the loop should terminate as soon as k*k equals or exceeds n.)

    ---

    I had gotten this:

    public void evenSquares(int n){
    int squares = k*k;
    for(int i=0; i<=n; i++){
    System.out.print(squares);
    }
    }

    --
    It says that it can't find "variable k" but I'm not quite sure what I'm doing wrong and where to fix it :$ Any help would be greatly appreciated!

  2. #2
    dragstang86 is offline Member
    Join Date
    Jun 2011
    Posts
    46
    Rep Power
    0

    Default Re: Need help with methods and 'for' loops?

    where is 'k' declared as a variable? Do you have the statement

    int k;
    or
    int k = 0;

  3. #3
    jammas615 is offline Senior Member
    Join Date
    Jul 2011
    Location
    Melbourne, Victoria, Australia
    Posts
    155
    Rep Power
    3

    Default Re: Need help with methods and 'for' loops?

    dragstang86 is right, you need to declare a variable before you use it.

  4. #4
    kzaman's Avatar
    kzaman is offline Member
    Join Date
    Oct 2011
    Location
    Dhaka, Bangladesh
    Posts
    4
    Rep Power
    0

    Default Re: Need help with methods and 'for' loops?

    you should write like followings:

    Snip: No spoon feeding. You have been warned multiple times. Please stop.
    Last edited by sunde887; 10-05-2011 at 10:27 PM.

  5. #5
    oliviaiona is offline Member
    Join Date
    Oct 2011
    Posts
    1
    Rep Power
    0

    Default Re: Need help with methods and 'for' loops?

    but the problem is stating that you can only print the positive squares, the code above will print all of the squares that are less than n, how could you format it so that only the positive ones are printed?

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. Replies: 1
    Last Post: 10-05-2011, 12:15 AM
  3. Replies: 8
    Last Post: 03-28-2011, 12:06 PM
  4. Replies: 20
    Last Post: 03-22-2011, 04:02 AM
  5. Replies: 4
    Last Post: 04-03-2009, 06:36 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •