-3

I am completely new to programming (java) and our teacher asks us to make some excercises in my programming lab.

Now I can't seem to find out how to write the correct method. This is the question: Write a method max that has two string parameters and returns the larger of the two.

I have

String string1, string2;
public max Strings(string1.length(), string2.length())
{
    if (string1.length()>string2.length)
    {
    return string1;
    else if (string1.length()<string2.length)
        return string2;
    }
}
2
  • 5
    You need to take some time to learn the basic syntax of Java. Read a Java introductory book or tutorial.
    – JB Nizet
    Mar 10, 2014 at 12:21
  • What is a larger string? You mean the longer one?
    – Axel
    Mar 10, 2014 at 12:24

3 Answers 3

1
public String max(String a, String b) {
    return (a.length() > b.length()) ? a : b;
}

There is the condition that both strings are of equal length which is not tested for, also null and empty strings,

2
  • i see where and what i messed up ;) thank you (same goes for the comment below) Mar 10, 2014 at 12:59
  • Stupid edit which has just made it hard for a learner to understand,
    – Mark Homer
    Nov 2, 2016 at 10:46
0
  • In Java, all functions - even static ones - must be in a class

  • Java function definitions are return-type then name then parameters

  • You must decide which string to return if they are the same length, or explicitly return NULL

0
public class LongerString {

    public static String max(String a, String b) {
        String maxString = "";
        if (a.length() > b.length())
            maxString = a + " is longer";
        if (b.length() > a.length())
            maxString = b + " is longer";
        if (a.length() == b.length())
            maxString = "Both strings have the same length";
        return maxString;
    }

    public static void main(String[] args) {
            System.out.println(max("hey", "hello")); // output: "hello is longer"
    }

}

As you can see, I've created a variable called "maxString" that will contain the string that is longer. "length()" get the character length of the string. If both of the strings have the same length, then "maxString" will equal "Both strings have the same length". Then, the function returns "maxString".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.