473,574 Members | 2,953 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using variables inside for loop

14 New Member
Hi,

I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here:
Expand|Select|Wrap|Line Numbers
  1.  
  2. class Exc
  3. {
  4.  Exc ()
  5.  {
  6.   System.out.println ("Haribol");
  7.  }
  8.  
  9.  static public void main ( final String [] args )
  10.  {
  11.   for ( int i = 0 ; i < 4 ; ++ i )
  12.   {
  13.    Exc e = new Exc ();
  14.   }
  15.  }
  16. }
  17.  
There is a problem with this code. Let me first tell you my intentions. I want to use the variable 'e' ( of type 'Exc' ) only inside the for loop. That is, I want to restrict its scope to the for loop. So I have declared it inside the loop. But I also want to initialize it with a new object of type 'Exc'. So I have written a declaration cum initializer statement. But since the statement is inside the for loop, it gets executed multiple number of times ( 4 times to be precise ). My intention was to have it executed only once.

There is one solution to this problem which is to use a counter or a sentinel that will signal the number of times that the loop has executed. Fortunately here, the for loop is using a 'built-in' counter namely 'i'. So the code now becomes:
Expand|Select|Wrap|Line Numbers
  1.  
  2. class Exc
  3. {
  4.  Exc ()
  5.  {
  6.   System.out.println ("Haribol");
  7.  }
  8.  
  9.  static public void main ( final String [] args )
  10.  {
  11.   for ( int i = 0 ; i < 4 ; ++ i )
  12.   {
  13.    Exc e;
  14.    if ( i == 0 ) e = new Exc ();
  15.   }
  16.  }
  17. }
  18.  
Another solution for this would be to enclose the for loop inside a code block delimited by '{' and '}' and declare the variable 'e' outside the for loop but inside the code block. The variable 'e' will also be initialized when it's declared. Here's what I mean:
Expand|Select|Wrap|Line Numbers
  1.  
  2. class Exc
  3. {
  4.  Exc ()
  5.  {
  6.   System.out.println ("Haribol");
  7.  }
  8.  
  9.  static public void main ( final String [] args )
  10.  {
  11.   {
  12.    Exc e = new Exc () ;
  13.  
  14.    for ( int i = 0 ; i < 4 ; ++ i )
  15.    {
  16.     //call some methods on 'e'
  17.    }
  18.   }
  19.  }
  20. }
  21.  
This way the variable 'e' will have its scope restricted to the for loop and also be 'initialized' only once.

But these solutions are somewhat artificial. Their design intentions are not immediately clear. Are there any elegant solutions for this design problem - something that is naturally expressed by the Java language ?
Jan 27 '09 #1
5 4038
JosAH
11,448 Recognized Expert MVP
Your second 'solution' fails because evertime the loop body is executed a new variable 'e' is defined and it will only be initialized when i == 0. Imho your third solution is fine because you don't create a new scope { ... } for nothing. It'd catch my eye.

kind regards,

Jos
Jan 27 '09 #2
jkmyoung
2,057 Recognized Expert Top Contributor
How about:
Expand|Select|Wrap|Line Numbers
  1. for ( int i = 0, Exc e = new Exc () ; i < 4 ; ++ i ) 
  2. {
  3. // operations on e. 
  4. }
Jan 27 '09 #3
JosAH
11,448 Recognized Expert MVP
@jkmyoung
You can't do that: an initialization list is limited to only one type. You try to introduce two types here: an int and an Exc.

kind regards,

Jos
Jan 27 '09 #4
sgurukrupagmailcom
14 New Member
Thank you, for your kind reply.

Warm Regards,
Ganesh
Jan 28 '09 #5
BSCode266
38 New Member
Do you really want to go through the for loop 4 times? If not you could always use a break; And i don't see whats wrong with the if(i==0) if you are only going to use it once.
Jan 31 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

8
2015
by: Derek Fountain | last post by:
I'm having trouble understanding the use of XSLT variables. I'm trying to add up the values from a set of elements. The code currently looks like this: <xsl:variable name="orderTotal"> <xsl:value-of select="0" /> </xsl:variable> <xsl:for-each select="item"> <xsl:variable name="orderTotal">
15
3216
by: lawrence | last post by:
Sorry for the dumb question but I'm new to Javascript. I wrote this script hoping to animate some div blocks on a page. You can see the page here: http://www.keymedia.biz/demo.htm Can anyone tell me why these DIVs don't drift to the left as they are supposed to? <script language="javascript">
8
2875
by: pertheli | last post by:
I am in a situation where only "goto" seems to be the answer for my program logic where I have to retry calling some repeated functions. Can anybody help in the usage of goto and its effect in local variables, as shown in the stripped code below void Process(){ int iMaxRetry = 100;
5
1666
by: elzacho | last post by:
I would like to (and commonly do) define my variables in the most specific scope I can. For example... int foo(int a, int b, int c) { /* don't declare temp here if we can help it */ ... for (i = 0; i < max; i++) {
9
2475
by: Javaman59 | last post by:
Using local declarations within a block often makes code more readable, but is it less efficient? eg... void P() { while (...) { int i = ...; bool b = ...; .... } }
23
6519
by: Tim Anderson | last post by:
Is this expected behavior? Winform with button and listbox: Dim i As Integer For i = 0 To 50 Dim s As String If i = 1 Then s = "Only once?" End If
39
2389
by: Gaijinco | last post by:
I have always felt that you should only declared variables as needed, and implicitily it seems many authors to encourage it, but the other day a friend told me that declaring variables inside a loop wasn't good practice, something like: for(int i=0; i<size-1; ++i){ int aux = array; array=array; array=aux; }
8
7502
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine, like this: for(var i=0; i<list; i++) { var name = list; }
14
2950
by: raylopez99 | last post by:
KeyDown won't work KeyPress fails KeyDown not seen inspired by a poster here:http://tinyurl.com/62d97l I found some interesting stuff, which I reproduce below for newbies like me. The main reason you would want to do this is for example to trigger something from an OnPaint event without resorting to boolean switches-- say if a user...
0
8237
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7817
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6454
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3741
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3752
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2245
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1060
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.