Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to pass variable values between successive for loops?

 
Ziya Bakan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I have two successive for loops and i need to pass one of the variables' value to an instance inside the other for loop.

for(int x=0; x< sentence.length(); x++) {

int i;
if (!Character.isWhitespace(sentence.charAt(x)))
i = x ;
break;

}

for (int i ; i < sentence.length(); i++) {

if (Character.isWhitespace(sentence.charAt(i)))
if (!Character.isWhitespace(sentence.charAt(i + 1)))

}

This is just a part of my program and my purpose is assigning the value of x (from the fĂ­rst for loop) to i variable(from the second for loop) so that i wont start from 0 but from the value of x(before breaking the first for loop)...Looking forward to your replies...Thank you so much in advance!!!
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could either declare your i variable outside of your first for loop or you could put your second for loop inside the if statement in your first for loop
 
fred rosenberger
lowercase baba
Bartender
Posts: 12185
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may want to search around on the term 'variable scope'. Basically, method variables can (and do) go 'out of scope' when you hit the closing brace of the block where they are defined. So:



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic