Java - Word Count True or False - java

i have a programming task using java...
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
int wordcount = 0;
for(int i = 0; i < sentence.length()-1; i++) {
if(sentence.charAt(i) == ' ' && Character.isLetter(sentence.charAt(i+1)) && (i > 0)) {
wordcount++;
}
}
wordcount++;
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}}
My question is how can i define the String sentence based on this condition:
If more than 3 words, it will be True.
If less than 4 words, it becomes False.
Thankyou so much for helping..

If I understand your question correctly...
/* returns string array of tokens (words in the sentence) after splitting by space */
String[] tokens = sentence.split(" ");
if(tokens.length() > 3) {
// true
} else {
// fasle
}

Let's have a look at the steps we should take in order to achieve your goal in a easier way;
First , let's count the number of words in your input string via
count function
Call the function by sending our input sentence
Function returns number of words Check the number of words for any
condition you desire
Therefore your code will work better like this;
public class CountWords{
public static void main(String[] args) {
String sentence = "Papa beauty lies in the eyes of beholder";
private bool coniditon;
int wordcount = count(sentencte);
if (wordcount<4) {
condition=False;
}
else if (wordcount>3) {
condition=True;
}
System.out.println("Total number of words: " + wordcount);
System.out.println(sentence.startsWith("P"));
}
public static int count(String sentence){
if(sentence == null || sentence.isEmpty()){
return 0; }
String[] words = sentence.split("\\s+");
return words.length; }
}
}
Good luck!

Related

Problem with infinitely looping text in a word generator

I'm making a Palindrome Generator. Basically the user inputs a word or sentence and the program outputs whether or not its a Palindrome, which is a word that is spelled the same forwards and backwards like "wow" or "racecar". My program works fine, however the output text will repeat itself like fifty times and I can't seem to figure out where the issue is without messing everything up. Help would be appreciated.
import javax.swing.JOptionPane;
public class palindromedectector {
public static void main(String[] args) {
String testStrings = "";
testStrings = JOptionPane.showInputDialog("Enter word: ");
for (int i = 0; i < testStrings.length(); i++)
{
System.out.print("\"" + testStrings + "\"");
if (isPalindrome(stripString(testStrings)))
System.out.println(" is a palindrome.");
else
System.out.println(" is not a palindrome.");
}
}
public static String stripString(String strip)
{
strip = strip.toUpperCase();
String stripped= "";
for (int i= 0; i< strip.length(); i++)
{
if (Character.isLetter(strip.charAt(i)))
stripped += strip.charAt(i);
}
return stripped;
}
public static boolean isPalindrome (String str)
{
boolean status = false;
if (str.length() <= 1)
status = true;
else if (str.charAt(0) == str.charAt(str.length()-1))
{
status = isPalindrome (str.substring(1, str.length()-1));
}
return status;
}
}
Main issue is that you run isPalindrome check for the same string in the loop, probably you wanted to run multiple checks
public static void main(String[] args) {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
String word = JOptionPane.showInputDialog("Enter word: ");
System.out.print("\"" + word + "\"");
if (isPalindrome(stripString(word))) {
System.out.println(" is a palindrome.");
} else {
System.out.println(" is not a palindrome.");
}
}
}
Also, the main functionality may be implemented in a shorter way:
// use regexp to get rid of non-letters
private static String stripString(String word) {
if (null == word || word.isEmpty()) {
return word;
}
return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}
// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
if (null == word) {
return false;
}
final int len = word.length();
if (len < 2) {
return true;
}
return IntStream.range(0, len/2)
.allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}
Basic problem: You are testing if the word is a palindrome testStrings.length() times, ie once for every letter in the word, rather than just once.
Remove the for loop in your main() method.

Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase

I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:
string = "good morning everyone"
n = 2
Output = gOod mOrning eVeryone
for (int x = 0; x < s.length(); x++)
if (x == n-1){
temp+=(""+s.charAt(x)).toUpperCase();
}else{
temp+=(""+s.charAt(x)).toLowerCase();
}
s=temp;
System.out.println(s);
}
Output: gOod morning everyone
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.
This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.
public class Test {
static String test = "This is a test.";
public static void main(String[] args) {
String[] words = test.split(" ");
String result = "";
for (String word : words) {
result += nthToUpperCase(word, 2);
result += " ";
}
System.out.println(result);
}
public static String NthToUpperCase(String s, int n) {
String temp = "";
for (int i = 0; i < s.length(); i++) {
if (i == (n-1)) {
temp+=Character.toString(s.charAt(i)).toUpperCase();
} else {
temp+=Character.toString(s.charAt(i));
}
}
return temp;
}
}
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.
toUpperCase(2, "good morning everyone");
private static void toUpperCase(int nth, String sentence) {
StringBuilder result = new StringBuilder();
for(String word : sentence.split(" ")) {
for(int i = 0; i < word.length(); i++) {
if(i > 0 && i % nth - 1 == 0) {
result.append(Character.toString(word.charAt(i)).toUpperCase());
} else {
result.append(word.charAt(i));
}
}
result.append(" ");
}
System.out.println(result);
}
gOoD mOrNiNg eVeRyOnE

Convert String to Reverse String Using Recursion in Java

Today I am trying to convert String to reverse String e.g(Cat Is Running into Running Is Cat) word by word not Character
public class ReverseString_ {
public static void reverse(String str) {
String[] a = str.split(" ");
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i] + " ");
}
}
public static void main(String[] args) {
reverse("Cat Is Running");
}
}
The following output is shown:
Running Is Cat BUILD SUCCESSFUL (total time: 0 seconds)
I am trying to convert String into reverse String same as above but through Recursion method but it seems too confusing. and display more errors. Can someone please help me understanding it. Many thanks
public static String reverse_recursion(String str) {
if (str == null)
return null;
else {
String Arry[] = str.split(" ");
int n = Arry.length - 1;
System.out.println(Arry[n] + "");
return reverse_recursion(Arry[n - 1]);
}
}
public static void main(String[] args) {
reverse_recursion("Cat Is Running");
}
This code show following output:
Running
Is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
This code do not print (0) index why? can someone help me to solve this error please
This solution might be helpful. The comments explain the code pretty much.
public static String reverse_recursion(String str) {
String[] arry = str.split(" ", 2); //Split into a maximum of 2 Strings
if (arry.length > 1) { //If there is more than 1 word in arry
//Return the reverse of the rest of the str (arry[1])
//and concatenate together with the first word (arry[0])
return reverse_recursion(arry[1]) + " " + arry[0];
}
return arry[0]; //If less than or equal to 1 word, just return that word
}
This should work:
public static String reverse(String s) {
int idx = s.indexOf(" ");
if (idx < 0) {
// no space char found, thus, s is just a single word, so return just s itself
return s;
} else {
// return at first the recursively reversed rest, followed by a space char and the first extracted word
return reverse(s.substring(idx + 1)) + " " + s.substring(0, idx);
}
}
public static void main(String[] args) {
System.out.println(reverse("Cat Is Running"));
}
You are sending the last element of the Array next time instead of the String without the previously printed String.
Replace your return statement with this it should work.
return reverse_recursion(n==0?null:str.substring(0,(str.length()-Arry[n].length())-1));

Word count returns 1 for empty file

This code is for counting words in the input. It works except when no words are in the input - it returns 1 and not 0. What is wrong here?
import java.util.Scanner;
public class Exercise12 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Input, Stop by #");
String input = kb.nextLine();
while (! input.equals("#")) {
wordCount(input);
input = kb.nextLine();
}
} //main
public static void wordCount(String countSpace) {
int count = 1;
for (int i =0; i < countSpace.length(); i++ ) {
if ((countSpace.charAt(i)) == ' ') {
count++;
}
}
System.out.println(count);
}
} // class Exercise12
To get everything right you should trim() your String to remove leading and trailing whitespaces. Then split the String at whitespace and count all non empty Strings. Empty Strings are caused by consecutive whitespaces.
Use Java 8:
public static void wordCount(String countSpace) {
System.out.println(Arrays.stream(countSpace.trim().split(" ")).filter(word->!word.isEmpty()).count());
}
You could use the split function like this:
public static void wordCount(String countSpace) {
String[] words = countSpace.split(" ");
int count = words.length;
System.out.println(count);
}
EDIT:
As #Jérôme suggested below, I added the trim function and a check for the empty input and now it works correctly. I also changed the string in the split function to the "\s+" regex, as #Aleks G suggested. Thak you for your corrections. See the updated code below:
public static void wordCount(String countSpace) {
String[] words = countSpace.trim().split("\\s+");
int count = 0;
if (!(words[0].equals(""))){
count = words.length;
}
System.out.println(count);
}
TL;DR: Use StringTokenizer:
public static void wordCount(String input) {
int count = new java.util.StringTokenizer(input).countTokens();
System.out.println(count);
}
Long explanation:
Your code is almost correct, however you initialise your count to 1. Then you increment it for every space character that you find. At the end of the input you do not have a space, thus you do not increment the count for the last word - and this compensates you starting with 1 and not 0. Yet, in case of empty input, you start with 1 and there's nothing to read - therefore you end up with a wrong value.
The first fix is simple: change the initialisation to be int count = 0:
public static void wordCount(String countSpace) {
int count = 0;
for (int i =0; i < countSpace.length(); i++ ) {
if ((countSpace.charAt(i)) == ' ') {
count++;
}
}
System.out.println(count);
}
The next problem is that you're not counting words, but rather word separators. What if there are two consecutive spaces between two words? Further, what happens if you encounter end of line or end of file? Your code will break on those.
Ideally, you should use a tokenizer to count your words, but as a minimum, you should count how may times you switched from a space/line-end to an alphanumeric character. Here's an example of using a Tokenizer:
public static void wordCount(String input) {
int count = new java.util.StringTokenizer(input).countTokens();
System.out.println(count);
}
You need to handle the case of empty inputs separately. In addition you should keep in mind that an input might contain two consecutive spaces or spaces at the beginning/end of the line, which shouldn't count for words.
With these special cases, the code would look like this:
public static void wordCount(String in){
boolean isspace = true;
int count = 0;
for(int i = 0; i < in.length(); i++)
{
//increment count on start of a word
if(isspace && in.charAt(i) != ' ')
{
count++;
isspace = false;
}
//reset isspace flag on end of a word
else if(!isspace && in.charAt(i) == ' ')
isspace = true;
}
System.out.println(count);
}
This code makes sure that words are only counted when they are actually encountered and repeated spaces get ignored.

Is there a method to count the number of times a variable has been previously stated in a string in java?

I'm trying to make a program that replaces any vowel with a number, counting up from 0 whenever a vowel occurs, while using loops
what I have so far:
int num = 0;
for (int number = 0; number <= (insert method that returns the number of times num occured in the string here / number of vowels of any type previously seen in the string); number ++)
{
num = number;
}
String word = "AEIOUaeiou87878alkjdaslwlejrlajflawjkflwj";
word = word.replaceAll("A", "" + num).replaceAll("E", "" + num)
.replaceAll("I", "" + num).replaceAll("O", "" + num)
.replaceAll("U", "" + num).replaceAll("a", "" + num)
.replaceAll("e", "" + num).replaceAll("i", "" + num)
.replaceAll("o", "" + num).replaceAll("u", "" + num);
System.out.println(word);
what is returned:
0123456789878780lkjd1slwl2jrl3jfl4wjkflwj
Does anybody know of a good way to make this work? Sorry if I'm not making much sense. I'm very new to coding.
Your problem is that you replace all instances of one letter at once. You need to have a counter for the vowels starting a 0, then increment it whenever you find one, then build a string out of that counter and the other non-vowel characters.
For example,
public static void vowelReplacer(String word) {
int vowelCount = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if ("aieou".contains(String.valueOf(Character.toLowerCase(c)))) {
sb.append(vowelCount++);
} else {
sb.append(c);
}
}
System.out.println(sb.toString());
}
I/O
public static void main(String[] args) {
vowelReplacer("AEIOUaeiou87878alkjdaslwlejrlajflawjkflwj");
// 01234567898787810lkjd11slwl12jrl13jfl14wjkflwj
}
The most important step is to split the word into an Array. Then you can check your vowels step by step and replace the char with an int if its necessary. If not just leave the char as it is.
But if you have a match, dont forget to add one to i (i++)
public static void main(String[] args) {
String word = "AEIObUaeiou87878alkjdaslwlejrlajflawjkflwj";
replaceVowel(word);
}
private static void replaceVowel(String word){
String[] chars = word.split("");
int i = 0;
StringBuilder replacedWord = new StringBuilder();
for (String oneChar : chars){
if(check(oneChar)){
replacedWord.append(String.valueOf(i));
i++;
}
else{
replacedWord.append(oneChar);
}
}
System.out.println(replacedWord);
}
private static boolean check(String oneChar){
oneChar = oneChar.toLowerCase();
if(oneChar.equals("a")||oneChar.equals("b")){ // ...the rest of your vowels
return true;
}else{
return false;
}
}
For checking your vowels you only need lowercase because we are able to change the String to lowercase just for that check. So you have less writing.

Categories