Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Print variable which only exists within for loop?

  1. #1
    Junior Member
    Join Date
    Jul 2014
    Posts
    29
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Print variable which only exists within for loop?

    There's loads of problems with this. What I'm trying to do.

    1) get a program to add the contents of an array together, preferably with a for loop and not the heavy handed version I've tried to use here.
    2) get the for loop's output just once, since it won't compile or recognise the variable outside of the loop.
    How do I make the loop's 'counter' variable available everywhere?


     
    public class retint {
     
    	public static void main(String[] args){
     
     
     
    		int[] onetoTen = {1,2,3,4,5,6,7,8,9,10};
     
    			for (int i=0; i<10; i++) {
     
    				int counter = (onetoTen[0] + onetoTen[1] + onetoTen[2] + onetoTen[3] + onetoTen[4] + onetoTen[5] +
    						onetoTen[6] + onetoTen[7] + onetoTen[8] + onetoTen[9]);
     
    				System.out.println(counter);
     
     
    		}
     
     
     
     
     
     
    	}

    Terrible code, I know. There has to be a more efficient way.


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    769
    Thanks
    0
    Thanked 145 Times in 128 Posts

    Default Re: Print variable which only exists within for loop?

    How do I make the loop's 'counter' variable available everywhere?
    By declaring it outside of the loop.

    By the way, I dont understand your calculation within the loop. You add all numbers 10 times?

  3. #3
    Member Ada Lovelace's Avatar
    Join Date
    May 2014
    Location
    South England UK
    Posts
    411
    My Mood
    Angelic
    Thanks
    27
    Thanked 61 Times in 55 Posts

    Default Re: Print variable which only exists within for loop?

    How do I make the loop's 'counter' variable available everywhere?
    Read up about scoping rules. Make the variable available to all of the method.
    Although this is quite bad practice as the loop counter declaration should
    reside within the for loop header.

    Wishes Ada xx
    If to Err is human - then programmers are most human of us all.
    "The Analytical Engine offers a new, a vast, and a powerful language . . .
    for the purposes of mankind
    ."
    Augusta Ada Byron, Lady Lovelace (1851)

  4. #4
    Junior Member
    Join Date
    Jul 2014
    Posts
    29
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Print variable which only exists within for loop?

    Okay, thank you both that worked fine, does that mean that it needs to be declared in main only? I tried it in main and that worked, but would it work if it were to be declared in another method?

    With the array, I'm basically trying to:
    1. declare array of numbers 1 to 10
    2. set up a for loop which cycles through the array and adds the elements together (such as 1+2+3+4+5+6+7+8+9+10)

    I can make it print out the numbers from one to ten, like this:

    public class retint {
     
    	public static void main(String[] args){
     
    		int[] onetoTen = {1,2,3,4,5,6,7,8,9,10};
     
     
    			for (int i=0; i<10; i++) {
     
     
    					System.out.println(onetoTen[0]++);
     
     
     
    		}
     
     
     
     
     
     
    	}
    }

    But it doesn't add them together. Obviously it won't based on the code but there must be a small modification I can make to get it to do that?

  5. #5
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    769
    Thanks
    0
    Thanked 145 Times in 128 Posts

    Default Re: Print variable which only exists within for loop?

    What you want to do is sum up the elements of the array.
    Think about it without writing code. Try to write the steps down one by one on a piece of paper.
    You have a list of numbers. You can always get 1 number at a time out of that list. How would you make the sum by hand?

    When you thought about that think how you could translate that into java code.

  6. The Following 2 Users Say Thank You to Cornix For This Useful Post:

    BenjaminJ (July 19th, 2014), GregBrannon (July 19th, 2014)

  7. #6
    Junior Member
    Join Date
    Jul 2014
    Posts
    29
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Print variable which only exists within for loop?

    	int[] onetoTen = {1,2,3,4,5,6,7,8,9,10};
    			int sum = 0;
     
    				for (int i=0; i<10; i++) {
     
     
     
    						sum +=onetoTen[0]++;
    						System.out.println(sum);

    I think I've got it. I just needed to store the result in a new variable to make it manipulable. Thank you!

  8. #7
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    769
    Thanks
    0
    Thanked 145 Times in 128 Posts

    Default Re: Print variable which only exists within for loop?

    There are still a few small problems.

    1) you should change your for loop to run until the end of the array instead of hardcoding a value:
    // this is bad
    for (int i=0; i<10; i++) {

    // this is good !
    for (int i=0; i<oneToTen.length; i++) {

    2) You are not actually summing up all values in your array. You never use your variable i.

    3) Why are you incrementing the values stored in the array?
    This last part here, does not make any sense to me:
    onetoTen[0]++;

  9. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,845
    My Mood
    Mellow
    Thanks
    239
    Thanked 721 Times in 707 Posts

    Default Re: Print variable which only exists within for loop?

    But you've missed an important advantage of having a loop control variable. Consider this:

    sum += onetoTen[i];

    Also, your indentation is inconsistent. It should look like this (open brace on the for() statement line is an option):
    int[] onetoTen = {1,2,3,4,5,6,7,8,9,10};
    int sum = 0;
     
    for (int i=0; i<10; i++)
    {
        sum +=onetoTen[i];
        System.out.println(sum);
    }

    And don't use hard coded values (sometimes called "magic numbers") whenever possible. An improved for() loop condition would be:

    for ( int i=0 ; i < onetoTen.length ; i++ )

Similar Threads

  1. How Do I print this shape with for loop
    By tomer567 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 20th, 2013, 03:48 AM
  2. Beginner : Using a loop to print object array
    By trancecommunity in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 5th, 2013, 05:31 PM
  3. For-loop: initialisation of variable, can't set variable to value zero?
    By Bitbot in forum Loops & Control Statements
    Replies: 4
    Last Post: July 15th, 2012, 02:32 PM
  4. Replies: 1
    Last Post: October 16th, 2010, 03:32 PM
  5. [SOLVED] how to print for-loop output to JTextArea
    By voltaire in forum AWT / Java Swing
    Replies: 2
    Last Post: May 13th, 2010, 02:43 PM