How to find the length of the last word in java? - java

I want to find the length of the last word to initially find the length of the second word in the phrase. here's my plan, If I find the length of the last phrase then in the for loop if I subtract x, it should give me the length of the second word always. This has to be done using for loop and a scanner, where the user inputs any phrase.
Basically, I need to know how to find the length of the last phrase. Thats what I need to know only.
here's my code:
else if (option == 2){
int counter = 0 ;
for (int x = 0; x < phrase.length() - x; x++){
//in the "int x = 0" i need to put the length of the last word
// in a phrase
char n = phrase.charAt(x);
if (n == x);
counter++;
}
System.out.print("Second word has "+counter+" letters");
}

With only the for-loop, length of last word in the phrase:
else if (option == 2){
int lastSpaceChar = 0;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ') { //Indicate space
lastSpaceChar = x;
}
}
//When loop is finished, it will have the index of the last space
//So if you take total length - last space, you'll get the last word
int lengthOfLastWord = phrase.length() - spaceChar;
System.out.print("Last word has " + lengthOfLastWord + " letters");
}
If you want the second word, you need to do the same, except find 1st and 2nd space, because characters between first 2 spaces form the 2nd word.
else if (option == 2){
int firstSpace = -1;
int secondSpace = -1;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ' && firstSpace == -1) { //Space found the first time
firstSpace = x;
} else if (n == ' ') {
//FirstSpace has already been found
//So this should be second
secondSpace = x;
break; //No need to look anymore, we have both spaces
}
}
//When loop is finished, you will have first 2 spaces
//Characters between first 2 spaces is 2nd word
int lengthOfSecondWord = firstSpace - secondSpace;
System.out.print("Second word has " + lengthOfSecondWord + " letters");
}
I'm assuming you're just learning, so this will do.
Of course, you should probably do error handling and look out for edge cases in actual practice.

The length of the last word in a sentence can be obtained like this:
public int getLengthOfLastWord(String sentence) {
if (sentence == null || sentence.length() == 0) {
return 0;
}
// Split the sentence into words on space(s).
String[] words = sentence.split("\\s+");
return words[words.length - 1].length();
}

To be accurate, you'll want to do more than just check for spaces between words, because if you are only looking for spaces then it is going to treat punctuation like commas and periods as part of the lengths of words. So your best bet is something like isAlphabetic().
If your plan is to loop through characters in the string (i.e. you don't want to use string functions), one very simple way (that wouldn't require you to change your code much) is to count forward through the array. The first time you find one where:
phrase.charAt(x).isAlphabetic()
is true, you know you've reached the beginning of the first "word" in the phrase.
Then you keep looking forward and when
!phrase.charAt(x).isAlphabetic()
Then you know you've reached the space between the first word and the second word. But there might be punctuation so you keep scanning forward until you're back to isAlphabetic() being true again, at which point you've reached the beginning of the second word. You now start counting characters until you find isAlphabetic() going false again (you've reached a space or punctuation). At which point you know you've reached the end of the second word, and now you can check your character count for how long it was.
This method doesn't count numbers, punctuation, spaces, and special characters as part of a phrase. So you might need to special-case it for things like an apostrophe in a contraction like "don't", but hopefully this gives you a general idea.
There are other approaches, but this is the closest to how you have your code right now. Obviously you can use String functions and get a shorter piece of code, etc, but you asked specifically for a version that conformed to your loop method.
int word_wanted = 2; // Want length of the second word. Or set to -1 if you want the last word.
int counter = 0; // How long is the current word
int on_word = 0; // What word number are we on
boolean in_word = false; // Are we currently in a word
for (int x = 0; x < phrase.length() - x; x++){
if (phrase.charAt(x).isAlphabetic()) {
if (!in_word) {
on_word++;
counter = 0;
in_word = true;
}
counter++;
} else {
if (in_word) {
in_word = false;
if (on_word == word_wanted) break; // Stop if we found the length of the word requested.
}
}
}
// counter now contains the length of the requested word. It can be returned
// as a return value from your method, or used for other purposes.

It is not clear from your question whether you want to find the length of the last word or the length of the second word from the start or the length of the second last word in a phrase. So, I've written solutions to all of these requirements. I've put enough comment in the code so that you can understand it easily.
Length of the last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int i;
// Start the loop from the end in the backward direction
for (i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
System.out.println("Length of the last word: " + (phrase.length() - i - 1));
break;
}
}
// If the loop terminated without finding any space, it means there is only one
// word in the phrase
if (i == -1) {
System.out.println("Length of the last word: " + phrase.length());
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the last word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning
Length of the last word: 7
Another sample run:
Enter option: 2
Enter phrase: Good
Length of the last word: 4
Length of the second word from the beginning:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of the second word: " + (i - index - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second word will be phrase.length() - index - 1
if (counter == 1) {
System.out.println("Length of the second word: " + (phrase.length() - index - 1));
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Hello world
Length of the second word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the second word: 7
Length of the second last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
// Start the loop from the end in the backward direction
for (int i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of second last word: " + (index - i - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second last word (which is the first word out of
// the two words) will be index (as the loop is running in the backward
// direction)
if (counter == 1) {
System.out.println("Length of second last word: " + index);
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of second last word: 7
Another sample run:
Enter option: 2
Enter phrase: Hello world
Length of second last word: 5

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

Hangman: How to compare and replace a dash with a letter found

I am learning Java, I know it exists several solutions on stackoverflow but I am stuck. I am trying to create a basic Hangman.
I would like to know how Could I replace a dash with a letter found?
Here is a demonstration:
The word to search is:no
I enter the letter n
You have 5 attempts.
--
Enter your letter: n
I enter the letter o
You have 4 attempts.
--
Enter your letter: o
Idem.
You have 3 attempts.
--
Enter your letter:
Here is my code:
Scanner input = new Scanner(System.in);
char letter = 0; // declares and initialises letter
String[] words = {"yes", "no"}; // declares and initialises an array of words to guess
String word = words[(int) (Math.random() * words.length)]; // chooses random word
boolean[] found = new boolean[word .length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word.length(); i++) {
if ( found[i] ) {
System.out.print(word.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
attempts--;
}
I have to add a loop perhaps?
I share you my code here => https://repl.it/repls/PeriodicLegitimateMatrix
You can use the indexOf(char) method in the String class to check whether the character was in the word.
It should look like this:
while (attemps > 0) {
//...
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
int characterPosition = word.indexOf(letter);//use a loop because the character could appear in more than one position in the word
while (characterPosition != -1) {//if indexOf(char) returns -1 it means the char was not found
found[characterPosition] = true;
characterPosition = word.indexOf(letter, characterPosition);//this time search the character starting from the last position to find the next one
}
attempts--;
}

JOptionPane not returning correct value

Arrays are not allowed, the function was working but just returning 0 as if it wasn't counting the correct inputted character, but now its giving me a "string out of range: 3"
This is supposed to run, open a window that asks me to input a string, in this case it's a word, and then another window opens asking me to input another string, in this case it's a letter. It then takes the second string (the letter) and tries to find how many times that letter occurs in the first string (the word).
For example, I compile, then run. After it is run, it opens a window, I input the word cat, then the second window opens and I input the letter A. I get a return window that tells me the letter A appears in the word cat 0 times. That's what WAS happening, now I'm just getting string out of bounds exception string index out of range: 3
import javax.swing.JOptionPane; // Need for JOptionPane
/*
This program is used to
get a word and a letter
from the user and count
and display the number of
times the letter appears
in the word.
*/
public class LetterCounter {
public static void main(String[] args) {
String userInput;
String userSentence;
char userChar;
int charCount = 0;
int index = 0;
userInput = JOptionPane.showInputDialog("Enter a String: ");
userSentence = userInput;
userInput = JOptionPane.showInputDialog("Enter a Character: ");
userChar = userInput.charAt(0);
for(index = 0; index < userSentence.length(); index++); {
if(userSentence.charAt( index ) == userChar) {
charCount++;
}
}
JOptionPane.showMessageDialog(null, userChar + " is used in "
+ userSentence + " " + charCount +
" time(s).");
System.exit(0);
}
}
Anyone know what is going wrong?
The problem is with the following code block in which you have put a ; after for loop:
for(index = 0; index < userSentence.length(); index++); {
if(userSentence.charAt( index ) == userChar) {
charCount++;
}
}
Just remove it as follows and it will work as expected:
for (index = 0; index < userSentence.length(); index++) {
if (userSentence.charAt(index) == userChar) {
charCount++;
}
}

I have to make a tweet tester in java, but can't figure out how to count the amount of times a character shows up in the tweet

Alright, so for a class I am taking I have to make a program that tests tweets. It asks you to input a tweet, then tells you if the tweet is valid (less than 140 characters), tells you the amount of mentions (indicated by the character #) and the number of hashtags (indicated by a #), and tells you whether or not it is a retweet (if it contains "RT:" it is considered a retweet).
I can tell whether it is a valid tweet and can tell if it is a retweet (I coded it so that if the index of "RT:" is greater than or equal to 0, it says it is a retweet), but can't figure out how to count the number of # and # in the string the user enters. I know how to find the index, but am having trouble finding out where to go from there. I don't know what to do as a next course of action. Is there a way to count the amount of a certain character in a string?
I know what the code is currently doing, outputting the index of the first time the character shows up, but I am lost on what else I could do. I thought that maybe I could truncate every letter before and including the # and use a loop to count the amount of times that I get an index for #, then do the same for the #, but I don't know how to truncate every letter before and including a certain character. Or is there a better option? Any help is appreciated
import java.util.Scanner;
import java.lang.Math;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet:");
String s = scan.nextLine();
int length = s.length();
if(length > 140)
System.out.println("Excess Characters: " + ( length - 140));
else{
System.out.println("Length Correct");
int at = s.indexOf('#');
System.out.println("Number of Mentions: " + (at));
int hash = s.indexOf('#');
System.out.println("Number of Hashtags: " + (hash));
if (s.indexOf("RT:") >=0)
System.out.println("The input was a retweet.");
else
System.out.println("The input was not a retweet.");
}}}
.indexOf will return the index of that character in your String.
That might not be the best approach to resolve your problem.
You could do something like this :
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) == '#') {
count++; //or whatever mechanism you want to keep track of those chars.
}
}
Improving slightly on Caleb's answer:
Since you know which two characters you need to count, '#' and '#,' you can have a counter for each and just iterate over the tweet once. Then you just check if a character is one you're looking for, and if it is, the counter is incremented!
int mentions = 0;
int hashtags = 0;
for(int i = 0; i < s.length; i++) {
if(s.charAt(i) == '#') {
mentions++;
} else if(s.charAt(i) == '#') {
hashtags++;
}
}
Now mentions and hashtags should have the countes of #'s and #'s respectively.
You can solve this problem by implementing a simple counting method:
public int charCount(char c, String tweet) {
int count = 0;
for(int i = 0; i < tweet.length()) {
if(tweet.charAt(i) == c) count++;
}
return count;
}
With this, you can count the number of times a character appears in a tweet.
System.out.println("Length Correct");
int at = charCount('#', s);
System.out.println("Number of Mentions: " + at);
int hash = charCount('#', s);
System.out.println("Number of Hashtags: " + hash);
if (s.indexOf("RT:") >= 0)
System.out.println("The input was a retweet.");
else
System.out.println("The input was not a retweet.");

Categories

Resources