简体   繁体   中英

I have a problem with methods on Java could I have some advice?

I was given the task of splitting my program which outputted the longest word in a sentence into a number of methods within the same class. I keep on trying out different ways but none seem to work. Could someone help me out? This is the program:

import java.util.Scanner;
public class Test{
    
    public static str getUserInput(Scanner sc) {
        System.out.print("Enter a string or sentence: ");
        // Return the string inputted by the user
        return sc.nextLine();
        return str;
    }

    public static void getlongestWord(str) { 
        Scanner str2 = new Scanner(str);  
        //Initialise longestWord with the first word in str
        String longestWord = str2.next();
        //Initiaise maxlen with length of first word in str
        int maxlen = longestWord.length();
        while(str2.hasNext())  //This loop will keep running till words are present
        {
            String word = str2.next(); //Storing next word in variable
            int len = word.length();    //Storing word's length
            if(len>maxlen)  //If this length is more than maxlen, longestWord and maxlen are changed
            {

                longestWord = word;  
                maxlen = len;
            }
        }
        return longestWord;
        return maxlen;
    }
    int longestWord;
    int maxlen;
    public static void getOutput (int longestWord) {
        System.out.println("The longest word is '" + longestWord );
    }

    public static void getOuput2 (int maxlen){
        System.out.println ("of length "+maxlen+" characters.");
    }
}

I left some comments in your code:

import java.util.Scanner;

public class Test {

    public static str getUserInput(Scanner sc) { // The return type should be of type String and not str.
        System.out.print("Enter a string or sentence: ");
        return sc.nextLine();
        return str; // you can't have a return statement immediately after another return statement :)
    }

    public static void getlongestWord(str) { // The method parameter is not of a valid type (it is not String)
        Scanner str2 = new Scanner(str);  
        String longestWord = str2.next();
        int maxlen = longestWord.length();
        while(str2.hasNext())
        {
            String word = str2.next(); 
            int len = word.length();    
            if(len>maxlen)
            {

                longestWord = word;  
                maxlen = len;
            }
        }
        return longestWord;
        return maxlen; // you can't have a return statement immediately after another return statement :)
    }
    int longestWord; // Instance variables should be declared at the top of the class
    int maxlen;

    public static void getOutput(int longestWord) { // Methods named {getSomething()} should return that something. This method returns void.
        System.out.println("The longest word is '" + longestWord);
    }

    public static void getOuput2(int maxlen) { // Focus on proper naming.
        System.out.println("of length " + maxlen + " characters.");
    }
}

I also wrote my own version of what you are trying to do:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        System.out.print("Enter a string or sentence: ");
        Scanner sc = new Scanner(System.in);
        processInput(sc);
    }

    public static void processInput(Scanner sc) {
        String sentence = sc.nextLine();
        String longestWord = findLongestWord(sentence);
        printInfo(longestWord);
    }

    public static String findLongestWord(String sentence) {
        String longest = "";
        for (String currentWord : sentence.split(" ")) {
            if (longest.length() < currentWord.length())
                longest = currentWord;
        }
        return longest;
    }

    public static void printInfo(String longestWord) {
        System.out.println("The longest word is '" + longestWord);
        System.out.println("of length " + longestWord.length() + " characters.");
    }

}

My solution is in no way a perfect solution so you could go ahead and understand the changes I made, and then implement your own changes. Remember: every class and method should be responsible for one thing only.

A simple way to do it is to split the string on whitespace and then iterate the resulting array to find the longest word. To find the longest word, you can start with the assumption that the first word is the longest and store it in a variable (eg String longestWord ) and whenever a word longer than this is encountered, replace the stored word with that word.

public class Main {
    public static void main(String[] args) {
        // Test string
        String str = "Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.";
        System.out.println("The longest word in the sentence: " + getLongestWord(str));
    }

    static String getLongestWord(String str) {
        // Split the string on whitespace
        String[] arr = str.split("\\s+");

        // Start with the assumption that the first word is longest
        String longestWord = arr[0];
        int maxLen = longestWord.length();

        for (String s : arr) {
            if (s.length() > maxLen) {
                maxLen = s.length();
                longestWord = s;
            }
        }

        return longestWord;
    }
}

Output:

The longest word in the sentence: programming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM