Java Error When correct code is put together

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2012-09-08T03:33:24Z Indexed on 2012/09/08 3:37 UTC
Read the original article Hit count: 120

Filed under:
|

I have a few string problems that I need to put together for a complete homework assignment. They all work correctly by themselves, but when I put them together in the main function, the last one that finds the smallest word in a string gives an error. Anyone know why?

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    //Length of Word
        String word1 = sc.next();
            System.out.println(word1.length());

    //Evens in one string odds in the other
        String word2 = sc.next();
            StringBuilder even = new StringBuilder();
            StringBuilder odd = new StringBuilder();
                for(int i = 0; i < word2.length(); i++){
                    if(i % 2 == 0){
                        even.append(word2.charAt(i));
                    }
                    else{
                        odd.append(word2.charAt(i));
                    }
                }
                System.out.println(even + " " + odd);

    //Diminishing Suffix
        String word3 = sc.next();
            for(int j = 0; j < word3.length(); j++){
                System.out.print(word3.substring(j, word3.length()) + " ");
            }
            System.out.printf("\n");

    //Letter Replacement
        String word4 = sc.next();
        String word5 = sc.next();
        String word6 = sc.next();

        String word7 =  word4.replace(word5, word6);
            System.out.println(word7);

    //How many times x appears in xstring
        String word8 = sc.next();
        String word9 = sc.next();
              int index = word8.indexOf(word9);
              int count = 0;
                while (index != -1) {
                    count++;
                    word8 = word8.substring(index + 1);
                    index = word8.indexOf(word9);
                }
                System.out.println(count);
                System.out.println();

    //Lexicographically smallest word
                String Sentence = sc.nextLine();
                String[] myWords = Sentence.split(" ");
                int shortestLengths, shortestLocation;

                shortestLengths=(myWords[1]).length();

                shortestLocation=1;

                for (int i = 1; i <myWords.length; i++) {

                if ((myWords[i]).length() < shortestLengths) {

                shortestLengths=(myWords[i]).length();

                shortestLocation=i;

                }

                }


                System.out.println(myWords[shortestLocation]);





}

}

Talking about the lexicographically smallest one

© Stack Overflow or respective owner

Related posts about java

Related posts about error-handling