Results 1 to 4 of 4

Thread: Looping methods

  1. #1
    WillHorne is offline Member
    Join Date
    Nov 2011
    Posts
    27
    Rep Power
    0

    Default Looping methods

    I'm playing around with methods and was wondering if there is a way to loop a method that has been called into the main method

    Java Code:
    import java.util.Scanner;
    
    public class squares3 {
    
    	
    	public static void main(String[] args) {
    		
    		
    		squares2.square(0);
    		squares2.sumOfSquares(0);
    		
    		
    		
    		
    	}
    	
    	public static int square (int n){
    		
    		return n*n;
    	
    		
    	}
    	
    	public static int sumOfSquares (int n)
    	{
    		{		
    		System.out.println("What Number?");
    		Scanner  sc = new Scanner(System.in);
    		n = sc.nextInt();
    		int sum = 0;
    		int i;
    		for (i = 1; i <=n; i++)
    			sum = sum + square(i);
    			System.out.println(sum);
    			
    			
    			return sum;
    	}	
    		
    	}
    }

    the method i want to loop is the
    Java Code:
    public static int sumOfSquares (int n)
    any helps is appreciated

    Thanks

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Looping methods

    The main() method is not special in any way: it is just a static void method taking an array of Strings as an argument.

    I'm not really sure what it is "to loop a method that has been called into the main method" - perhaps you could say what you are trying to do, rather than how you are trying to do it.

  3. #3
    WillHorne is offline Member
    Join Date
    Nov 2011
    Posts
    27
    Rep Power
    0

    Default Re: Looping methods

    the sum of squares method takes all the squared numbers from one to N and adds them together. the user can say what value N is. what i want is to have the user keep imputing the value of N after the squares have been calculated

    i'm not sure if i'm making myself clear

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Looping methods

    One way would be to call sumOfSquares() within a loop in main().

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. Java Noob, trying to call methods from another methods
    By gabrielpr12 in forum New To Java
    Replies: 8
    Last Post: 11-17-2011, 09:07 PM
  3. Replies: 1
    Last Post: 10-23-2011, 12:37 PM
  4. Replies: 1
    Last Post: 10-05-2011, 12:15 AM
  5. Help with While and For Looping
    By gmoney8316 in forum New To Java
    Replies: 2
    Last Post: 03-03-2010, 10:54 PM

Posting Permissions

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