[Solved] Accessing scope of a variable once declared outside class


import java.util.Arrays;

public class Kata {
public static int findShort(String s) {

int shortestLocation = null;

this ^^ line needs to be initialized to an integer… not ‘null’ 0 is fine

String[] words = s.split("");
int shortestLength=(words[0]).length();
    for(int i=1;i<words.length;i++){

your problem starts here ^^ you never iterate through all of the words as you stop at i<words.length the problem with that is you begin at i=1. for loops work like this for (begin here; until this is not met; do this each time) when i=words.length the condition is no longer met.

   if ((words[i]).length() < shortestLength) {
        shortestLength=(words[i]).length();
       shortestLocation=shortestLength;
    }

    }

 int p= shortestLocation;

No need to initialize p here… just return shortest location.

 return p;
        }
  }

that leaves the final code like this

import java.util.Arrays;

public class Kata {
public static int findShort(String s) {

int shortestLocation = 0;
String[] words = s.split("");
int shortestLength=(words[0]).length();
    for(int i=0;i<words.length;i++){
      if ((words[i]).length() < shortestLength) {
        shortestLength=(words[i]).length();
        shortestLocation=shortestLength;
      }

    }

 return shortestLocation;
        }
  }

Keep in mind, to get a ‘good’ result it HEAVILY weighs on the words list

As pointed out in the comments initializing your original ‘int p’ could help with debugging.

6

solved Accessing scope of a variable once declared outside class