简体   繁体   English

我对 Java 上的方法有疑问,可以给我一些建议吗?

[英]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.要找到最长的单词,您可以假设第一个单词是最长的,并将其存储在一个变量中(例如String longestWord ),只要遇到比这个更长的单词,就用该单词替换存储的单词。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在 Java 上实现 try and catch 块时遇到问题,我可以就如何 go 提供一些建议吗? - I have a problem with the implementing a try and catch block on Java, could I have some advice on how to go about it? 我在将我的 Java 程序拆分为同一 class 中的单独方法时遇到问题,我可以就如何 go 提供一些建议吗? - I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it? 我对理解一些 Java 代码有疑问 - I Have a problem with understanding some Java code 关于将方法引入我的工资计划,我可以得到一些指导吗? - Could I have some guidance on introducing methods into my wages program? 我有一个 Java 问题 - 它没有找到一些 package 或类 - I have a Java Problem - It is not locating some package or classes 我有左联接JPQL的一些问题 - i have some problem with left join JPQL 我对 java SSHClient class 有问题,特别是 Expect 方法没有按预期返回数据,会发生什么? - I have a problem with the java SSHClient class, specifically the Expect method does not return data as espected, what could be happening? 我对Java编译器有一些疑问 - I have some questions about Java compiler 我有一些关于在Java中进行转换的问题 - I have some issue about casting in java 我在Java中遇到与“ActionEvent”和“actionPerformed”有关的问题 - I have a Problem in Java relating to “ActionEvent” and “actionPerformed”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM