-1
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

public class FindDuplicates {
    
    public static void main(String[] args) 
    {
        String StringLetters = "aaabbbccc";
        List<String> NewList = new ArrayList<String>(Arrays.asList(StringLetters.split(",")));
//      System.out.print(NewList);
//      System.out.print(NewList.size());
        char CharA = 'a';
        int count = 0;
        for(int i = 0; i < NewList.size(); i++);{
            if (NewList.indexOf(i) == CharA);{
                System.out.print(i);
            }
        }
        }
}

Im building a program that counts duplicate values in a Java string. However, I receive "i cannot be resolved to a variable" even though its initialized within the for loop? Any guidance is appreciated.

  • 2
    No it isn't because your loop body is empty and the next part is just a scope block! The reason for that is the extra `;` that snuck in between the `)` and the `{` of your loop. (you have the same issue with your `if` by the way.) – CherryDT Sep 09 '21 at 22:14

2 Answers2

0

Remove the ; in for(int i = 0; i < NewList.size(); i++); line.
This actually makes the i defined inside for(int i = 0; i < NewList.size(); i++); only while it becomes not defined inside the

if (NewList.indexOf(i) == CharA);{
    System.out.print(i);
}

block

Prophet
  • 32,350
  • 22
  • 54
  • 79
0

for(int i = 0; i < NewList.size(); i++);{

The semicolon right at the end there comprises the block of things to do when looping. In other words, your for loop does nothing.

You then have a { which just starts a block. This is legal java. Try it:

public void test() {
    int x = 5;
     { // let's just start a block for no reason
        System.out.println(x);
     }
}

That compiles and runs just fine.

The i exists in its scope (which is the 3 parts of your for declaration, as in, within the (), and within the body of the for loop, which in your case is just the semi-colon), and ceases to exist afterwards. That { counts as 'afterwards', here.

Solution: Remove the semi-colon.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72