简体   繁体   English

这个For循环有什么问题?

[英]What's wrong with this For loop?

I can't get this program to count the spaces, I have a feeling there is a logic error in the loop, but I am too inexperienced to figure it out myself. 我无法获得该程序来计算空间,我感觉到循环中存在逻辑错误,但我自己经验不足。 Any tips? 有小费吗?

System.out.print("Enter a string: ");
String myString = keyboard.next();
int numBlanks = 0;

//find string length
int length = myString.length() - 1;
System.out.println("length " + length);

for(int sequence = 0; sequence >= length; ++sequence);
{

    if(myString.charAt(length)==' ')
    {
        numBlanks += 1;
        length -= length;
    }
    else 
        length -= length;

}

There are few bugs I can see: 我可以看到几个错误:

Semicolon at the end of for loop . for循环末尾的分号 Remove it. 去掉它。

Next 下一个

sequence >= length

should be 应该

sequence <= length

and

if(myString.charAt(length)==' ')

should be 应该

if(myString.charAt(sequence)==' ')

and you need to change length at all as you are already changing sequence . 并且您已经在更改sequence时完全需要更改length

So we get: 这样我们得到:

for(int sequence = 0; sequence <= length; ++sequence) {

    if(myString.charAt(sequence)==' ') {
        numBlanks += 1;
    }
}

sequence >= length is spoken aloud as " sequence is greater than or equal to length ." sequence >= length大声说为“ sequence大于或等于length It is initialized to zero. 初始化为零。 When will it be greater than or equal to length ? 什么时候大于或等于length

In addition to the errors others have pointed out, there are violations of convention here; 除了其他人指出的错误之外,这里还有违反约定的情况。 you're calculating the length as n - 1, and then comparing <= (well, >=, but should be <=). 您将长度计算为n-1,然后比较<=(好吧,> =,但应为<=)。 Typically, unless there is very good reason, our for loops look like this: 通常,除非有很好的理由,否则我们的for循环如下所示:

for (int i = 0; i < n; i++) {
    ...
}

In your case, this would be expressed as: 就您而言,这表示为:

for (int i = 0; i < myString.length(); i++) {
    ...
}

It is also conventional to stick with "i" as the loop variable, unless there's good reason to use another; 除非有充分的理由使用另一个变量,否则通常也将“ i”作为循环变量。 in your case, "sequence" is just confusing. 在您的情况下,“顺序”只是令人困惑。

First issue: 首要问题:

change 更改

for(int sequence = 0; sequence >= length; ++sequence);

to

for(int sequence = 0; sequence <= length; ++sequence);  //flipped >= to <=

Second issue: 第二期:

change 更改

I am too inexperienced to figure it out myself.

to

This will be some good practice for debugging.  //int confidence should never be negative

:D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM