Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse a variable without initializing a new one in for loop in java?

I was writing a function in java which counts the number of characters after white spaces in a string. This problem might sound trivial to some of you.

public int countAfterSpaces(final String a){
   int position = 0; // escapes leading whitespaces
   while(position<a.length() && a.charAt(position)==' ') position++;

Now I want to reuse this variable (position) in a for loop without creating a new one (i) in the initialization statement. Currently I am doing this.

   int count = 0;
   for (int i=position; i<a.length; i++) count++;
   return count;
}
like image 832
Aditya Avatar asked Apr 08 '26 08:04

Aditya


1 Answers

You don't need to declare a new variable:

for (; position<a.length; position++) count++;

You can leave any field of the for loop blank.

Or better yet, why not:

count = a.length - position;
like image 148
Daniel M. Avatar answered Apr 10 '26 22:04

Daniel M.