如何在不初始化Java中for循环的情况下重用变量? [英] How to reuse a variable without initializing a new one in for loop in java?

查看:108
本文介绍了如何在不初始化Java中for循环的情况下重用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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++;

现在,我想在for循环中重用此变量(位置),而不在初始化语句中创建新的变量(i).目前,我正在这样做.

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;
}

推荐答案

您无需声明新变量:

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

您可以将for循环的任何字段留空.

You can leave any field of the for loop blank.

或者更好,为什么不呢?

Or better yet, why not:

count = a.length - position;

这篇关于如何在不初始化Java中for循环的情况下重用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆