jeudi 28 mars 2019

I don't understand why I get this error, error: 'else' without 'if' [on hold]

I'm working an assignment from my Computer Science class and basically, you've gotta make a program that allows the user to input some random words and the algorithm you've made should return the longest word of the three provided by the user.

Here's what I've gotten so far:

import static java.lang.System.*;
import java.util.*;

// public class
public class Java2507
{
    public static void main(String[] args)
    {
        Problem07 answer = new Problem07();
        Scanner scan = new Scanner(in);

        out.print("Enter word1 --> ");
        String word1 = scan.nextLine();

        out.print("Enter word2 --> ");
        String word2 = scan.nextLine();

        out.print("Enter word3 --> ");
        String word3 = scan.nextLine();

        out.println();
        out.println("The longest word is " + answer.findLongest(word1, word2, word3));
    }
}


class Problem07
{
    String answer;
    String findLongest(String w1, String w2, String w3)
    {
        if(w1.length() > w2.length())
        {
            if(w1.length() > w3.length())
            {
                answer = w1;
            }
            return answer;
        }


        else if(w2.length() > w1.length())
        {
            if(w2.length() > w3.length())
            {
                answer = w2;
            }
        }
        return answer;

        else   //  <------ this is where I get the error
        {
            if(w3.length() > w2.length())
            {
                answer = w3;
            }
            return w3;
        }
    }
}

If any of you are more advanced in java programming, your help will be appreciated.

Aucun commentaire:

Enregistrer un commentaire