1

Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;

public class Test {
    public static void main(String[] args) {
        String str="Chocolate";
        int n=2;
        String x=frontTimes(str,n);
    }

    public static String frontTimes(String str, int n) {
        if(str.length()==1){
            String sub=str;
        }
        if(str.length()==2){
            String sub=str.substring(0,2);
        }
        else{
            String sub=str.substring(0,3);
        }
        String sub=str.substring(0,3);// This statement works. But without this, I get an error. Why does it not enter the else condition without this line?
        String result="";

        for(int i=0;i<n;i++){
            result=result +sub;
        }
        return result;
    }
}
Siam
  • 19
  • 1
  • Take a look at [What is scope in Java](https://stackoverflow.com/questions/38177140/what-is-scope-in-java) – Thiyagu Jan 03 '21 at 07:22
  • 1
    If you are asking why you get a **compilation** error when you remove the line with the comment, it is because the earlier declarations of `sub` are all out of scope. You need to read about the scope of a declaration, and what that means. – Stephen C Jan 03 '21 at 07:22
  • Since the str has been declared in main and it is being passed in the frontTimes method, I am not sure why it is out of scope. Without the commented line I get a compilation error but with the commented line I see that my if-else statements get executed through debugging. Can you please clarify? – Siam Jan 03 '21 at 07:38
  • The 3 previous declarations of `sub` are each within a `{ ... }` block. The scope of a variable declared in a `{ ... }` block ends at the end of the block. Therefore, when you try to refer to `sub` in the `for` loop, the compiler (correctly) says it can't resolve the symbol. – Stephen C Jan 03 '21 at 08:02

0 Answers0