Reputation: 23
I am new to Java and I need to solve an exercise that requires the following:
For a string that the user inputs, return the largest word (so far so good here)
But, it should take into account that numbers and symbols are not words.
For example: Hello, my name is Jonathan and my phone is 0123456789
should return "Jonathan"
as longest word.
Example 2: H3llo W0rld, Java 1s fun!
, should return "Java"
as longest word.
In my pseudo-code I thought about the following:
A) Request input from user.
B) While input invalid, loop.
C) Scan the input
D) Separate the words by the spaces, or tokens.
E) If Word contains just letters A-Z && a-z do the following code:
e1) Check for longest word, with a for.
e2) Print result
F) else if: move to the next word.
Here is the code that I have so far. As you see, many parts are taken from here and adapted to the code. The "Find the longest in array" is a popular subject, yet I am not able to do the checking for the alphabetical characters. Any help will be welcomed.
The problem is that I don't know how to implement the part that checks for letters.
Code:
package longestword;
import java.util.Scanner;
public class LongestWord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
//looping for non empty strings
int largestLength = 0;
String largestWord = "";
String userinput = sc.nextLine();
while (userinput.equals("")) {
System.out.println("Please insert a String: ");
userinput = sc.nextLine();
}
for (String b : userinput.split(" ")) {
if (largestWord.length() == 0) {
largestLength = b.length();
largestWord = b;
} else if (b.length() >= largestLength) {
largestLength = b.length();
largestWord = b;
}
}
sc.close();
System.out.println("Longest Word: " + largestWord);
}
public boolean isAlpha(String userinput) {
char[] chars = userinput.toCharArray();
for (char c : chars) {
if (!Character.isLetter(c)) {
return false;
}
}
return true;
}
}
/*
char c = '*';
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
}
*/
Upvotes: 2
Views: 228
Reputation: 311338
A possibly easier approach could be to split the string by any non-letter character, and let Java's streams do the heavy lifting for you:
String longestWorld =
Arrays.stream(userInput.split("[^a-zA-z]"))
.max(Comparator.comparing(String::length).reversed())
.orElse(null);
Upvotes: 1
Reputation: 393831
Just change your isAlpha
method to static
and use it as follows:
for (String b : userinput.split(" ")) {
if (isAlpha(b)) {
if (largestWord.length() == 0) {
largestLength = b.length();
largestWord = b;
} else if (b.length() >= largestLength) {
largestLength = b.length();
largestWord = b;
}
}
}
Upvotes: 1