Results 1 to 4 of 4

Thread: FOR Loop

  1. #1
    kerbdog is offline Member
    Join Date
    May 2011
    Posts
    1
    Rep Power
    0

    Question FOR Loop

    Having trouble with my For Loop. It keeps Looping.:confused:

    Java Code:
    import java.util.Scanner;
    
    public class tempcalc {
    
    	/**
    	 * @param args
    	 */
    	public static void intro()
    	{
    		System.out.println("Welcome to TempCalc.");
    		System.out.println("Reading temperature values for 12 months.");
    	}
    	
    	public static void temp()
    	{
    		Scanner input = new Scanner(System.in);
    		int tempgroup[];
    		int index;
    		int month;
    		
    		tempgroup = new int [12];
    		for (index = 0; index < 12; index = index + 1) 
    		{
    			for (month = 1; month < 13; month ++)
    			{
    			System.out.println("Please enter the value for month " + month);
    			tempgroup[index] = input.nextInt();
    			}
    			
    		} 
    			
    			
    	}
    
    
    	public static void main(String[] args) 
    	{
    		intro ();
    		temp ();
    	}
    }

  2. #2
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    384
    Rep Power
    4

    Default

    That one should loop 156 times. Does it loop more than that?

    EDIT: Correction, 144 times.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Why are you using a nested loop? It wot go for ever, however; it will loop 12 * 12 times, or 144. I suspect you meant to only use a single for loop which gets the temp for each month.

  4. #4
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    You have a loop that fills the tempgroup array with 12 month values which is inside another loop that runs 12 times, so you fill (overwrite) the array 12 times (total of 144 values entered).

    If you want to loop 12 times and prompt with the month number, remove the inner month loop and just use the index + 1 as the month number.

Similar Threads

  1. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM
  2. [Q] Loop issue (while loop)
    By iriscience in forum New To Java
    Replies: 9
    Last Post: 01-31-2011, 04:21 PM
  3. Convert do while loop to for loop
    By sandeeptheviper in forum New To Java
    Replies: 3
    Last Post: 01-03-2011, 12:37 PM
  4. Replies: 5
    Last Post: 04-30-2010, 05:05 PM
  5. while-loop stopping on first loop
    By davester in forum New To Java
    Replies: 6
    Last Post: 06-26-2009, 08:46 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
  •