Why cannot we use static keyword inside a method in java?

Java program, use a public static method called 'longest'?

  • Hi there, Im only a beginner so be nice :) I have been asked to write a program which outputs the longest word (which i have done) But I need to set it in a 'public static method called longest' which takes 2 string paramiters and returns the longest. As you will see below i have a working program which outputs what I need, i just dont know how to set it into a public static method :( package assignment3; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Longer { public static void main(String[] args) throws IOException { String sentence; String word; String longest = ""; System.out.print("Enter 2 words "); BufferedReader inputLine = new BufferedReader(new InputStreamReader(System.in)); sentence = inputLine.readLine(); Scanner keyboard = new Scanner(sentence); while (keyboard.hasNext()) { word = keyboard.next(); if (word.length() > longest.length()) { longest = word; } } System.out.print("" + longest + "\n"); } }

  • Answer:

    The method: public static String longest(String s1, String s2){ if(s1.length > s2.length){ return s1; } else { return s2; } }//end of method To use this in your code, take out the if statement in the while loop and do this: longest = longest(word, longest); I hope that helps.

Tomas at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

The method: public static String longest(String s1, String s2){ if(s1.length > s2.length){ return s1; } else { return s2; } }//end of method To use this in your code, take out the if statement in the while loop and do this: longest = longest(word, longest); I hope that helps.

TheFoxAn...

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.