mercredi 12 février 2020

How to find shortest word in a java string without using arrays?

I'm trying to use the same format of this code which I followed through a tutorial. It will print the longest word as well as the length of the longest word. The tutor told me that to find the shortest word I have to flip the if statement to be less than ('<') instead of greater than... however, after I enter any string, when I run the program it returns:

"Shortest Word: "", length: 0"

I'm not sure how to fix this so it looks for an actual word and not an empty character.. I'd like to follow the same logic here without using arrays as well.

Scanner in = new Scanner(System.in);

System.out.println("Please enter a phrase: ");
String phrase = in.nextLine();


String w = "";
String lw = "";       
int l;
char ch;


phrase = phrase + " ";
l = phrase.length();
int i;
for (i=0; i < l; i++) {
    ch = phrase.charAt(i);
    if(ch != ' ') {
        w = w + ch;
    } else {
        if(w.length() > lw.length()) {
            lw = w;
        }
        w = "";
    }
}

System.out.println("Longest Word: \"" + lw + "\", length: "+ lw.length());

Aucun commentaire:

Enregistrer un commentaire