I need to count the number of words and I am assuming the correct way to do it is by calculating the number of times that the previous character in a string is not a letter (ie other characters) because this is to assume that there would be colons,spaces,tabs, and other signs in the string.
So at first my idea was to loop through each character and count how many times that you will not get a letter of an alphabet
for(int i = 0; i < string.length(); i++) {
for(int j = 0; i < alphabets.length(); j++) {
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
}
}
However I will always get an array out of bounds because of this. So, I kinda need a little help or another way that can actually be more efficient.
I thought of using Matches to only [a-zA-z] but I'm not sure how do I handle a char to be comparable to a string in counting how many times it occurs.
Thank you
You can use String.split() to convert the string into an array, with one word in each element. The number of words is given by the length of the array:
int words = myString.split("\s+").length;
Your suggestion to use a regex like "[A-Za-z]" would work fine. In a split command, you'd split on the inverse, like:
String[] words = "Example test: one, two, three".split("[^A-Za-z]+");
EDIT: If you're just looking for raw speed, this'll do the job more quickly.
public static int countWords(String str) {
char[] sentence = str.toCharArray();
boolean inWord = false;
int wordCt = 0;
for (char c : sentence) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
if (!inWord) {
wordCt++;
inWord = true;
}
} else {
inWord = false;
}
}
return wordCt;
}
This problem is slightly more complicated than your algorithm allows.
What if there are two or more spaces in a row?
What if the string starts or ends with whitespace (or non-word characters)?
This looks like homework, so I don't want to provide any code. I suggest an alternative approach which is simpler to think about.
Walk through the characters in the string, one by one.
Do something to remember if you are currently scanning a word or if you are not currently scanning a word.
Do something to determine when you enter or leave a word, and increment your counter accordingly.
The reason you are getting an IndexOutOfBoundsException is probably because when i is 0 your inner loop will have string.charAt(i-1) which will throw an exception since 0-1 is -1. If you fix that your method might work, although you can use more efficient techniques.
Addressing the code directly, your first loop has i=0 as the first value of i, but then you ask for
string.charAt(i-1) = string.charAt(-1),
which is where your array-out-of-bounds is coming from.
The second loop has another problem:
for(int j = 0; i < alphabets.length(); j++) {
You may also want to consider apostrophes as parts of words as well.
Use just like this
String s = "I am Juyel Rana, from Bangladesh";
int count = s.split(" ").length;
if (string.charAt(i-1) == alphabets.charAt(j)) {
counter++;
}
You are incrementing the counter if the character is some alphabet character. You should increment it if it is no alphabet character.
The following program will count the number of words in a sentence. In this program, we are counting alphabets just after space. The alphabet can be of lower case or upper case. We are inserting a space at the beginning since people don't start a sentence with space. We also need to take care that any special character or number should not be counted as a word.
`import java.util.Scanner;
public class WordSent {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter the sentence");
String str=in.nextLine();
String space=" ";
String spaceword=space.concat(str);
int count=0;
for(int i=0; i<spaceword.length()-1;i++)
{
for (int k=0; k<=25; k++)
{
if(spaceword.charAt(i)==' '&& (spaceword.charAt(i+1)==((char)(65+k)) || spaceword.charAt(i+1)==((char)(97+k))))
{
count++;
}
}
}
System.out.println("Total number of words in a sentence are" +" : "+ count);
}
}`
Related
I am trying to have my code output the exact number of times a certain character is said in an inputted sentence (For example e).
I tried using a char and for statement so its able to count but it gives me the wrong value
int countChar;
char e = '\0';
String str;
int count = 0;
System.out.println("input your sentence:");
str = in.next();
for(i=0; i < str.length(); i++)
{ if(str.charAt(i) == e)
count++;
}
System.out.println(count);
You need to change if(str.charAt(i) == e) to if(str.charAt(i).equals("e")), you don't really require a variable for this. You just require the quotation marks, and since you are comparing a string, you should use the above String.equals() method.
If you are looking for uppercase letters as well, use the || (OR) operator and do the same but replace the lowercase e with an uppercase
You should use 'e' instead of '\0' when comparing the characters
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
for(count=0;count<x;count++) {
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
}
}
}
All this program does is print out the second to last character of the word that the user enters. I'm confused as to why it is doing this and want to know how to print out the whole word backwards. Someone help please.
You don't need a loop to reverse a string.
Ref - StringBuilder#reverse
Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());
If you want to print characters in reverse, then forget the substring-ing.
String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
System.out.println(word.charAt(count));
}
Take count1=x; assignment out of the loop. Also make count--; after printing the letter.
You are correct up until x = word.length(). It is printing the second from last character because you keep setting the value of count1 to length of word and you substract it by 1. Therefore, it keeps referring to the second last character. To fix that, do the following instead:
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.println(c);
count1--;
}
Every time the loop is running, you are resetting the count1 value to x (count1=x). So c will always be the same value.
To make this work, try taking count1 = x out of the loop so that every time the loop is running, count1 value will be reduced as expected providing the required sub-string.
Into the loop for(count=0;count<x;count++)
Every loop you did the same thing
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
This block has no relation with the loop!
Thats why you are getting the second last character!
To fix this:
Solution 1: (Just reverse the String)
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
or Solution 2: (Using loop using your code)
x=word.length();
for(count= x-1; count >= 0; count--) {
c = word.substring((count)-1, count);
System.out.print(c);
}
If at all you want to do it the hard way by traversing, do the following changes.
for(count=x;count>=0;count--) {
System.out.println(word.substring(count - 1,count));
}
Update: You can use charAt#String to easily get the character at some position.
for(count=x-1;count>=0;count--) {
System.out.println(word.charAt(count));
}
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment_4_Piglatin {
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
String vowels = "aeiou";
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
if (vowels.contains(String.valueOf(word.charAt(index)))) {
System.out.print(index);
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
}
}
}
System.out.println(firstVowel);
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:
String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
if(vowels.contains(String.valueOf(word.charAt(i)))){
System.out.println(word.charAt(i));
break;
}
}
Please note that you need to do toLowerCase on the actual word in order for contains to work.
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.
Think of this example: hello
The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.
However, if you only have one vowel, your program will "work".
What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.
The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:
System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:
firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.
So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
ArrayList<Character> vowels = new ArrayList<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
char indchar = word.charAt(index);
if (vowels.contains(word.charAt(index))) {
System.out.println(index);
firstVowel = Character.toString(word.charAt(index));
System.out.println(firstVowel);
index = word.length();
}
}
}
}
}
This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
I am trying to get the minimum length of the word in the code, without it counting punctuation marks and such. how do i do that? Also, I will get rid of the main method as it will be added automatically. How do i make the program automatically add a space after the last word?
public class WordCounts
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.nextLine();
System.out.println("minLength");
int minLength=in.nextInt();
System.out.print("Your sentence has " + countWords(sentence,minLength)+ " words.");
}
public static int countWords(String str, int minLength)
{
int count = 0;
int c=0;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) != ' ')
{
if(str.charAt(i)>='a' && str.charAt(i)<='z') //to check only for alphabets.
c++;
}
if(c>=minLength)
{
count++;
c=0;
}
}
return count;
}
}
You have to pass minLength as a parameter to the countWords function. That way, you will be able to access this variable in the countWords function. You will also want to loop through the string character by character and keep track of how many letters you have seen, call it "numLetters". Check if the character is present in the string "aAbBcC....yYzZ" to ensure it is a letter, and if it is present, then add 1 to "numLetters". If you reach the end of the input or reach a space, then check if numLetters is greater than minLength, and if so, add 1 to count. Reset numLetters to 0 and keep going until you reach the end of the string.
e.g. to get the character:
for (int i = 0; i < str.length(); i++){
char c = str.charAt(i);
}
I think I understood your problem statement correctly. Correct me if I am wrong.
You want to check that the length of entered string should be greater than the minimum entered length. For that you need to pass the minLength variable to the method countWords. And then you are checking that the character is valid or not using if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
Updated method
public static int countWords(String str, int minLength)
{
int count = 1;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ' && str.length()>=minLength)
{
count++;
}
}
return count;
}
In your main method, take input using Scanner
int minLength=in.nextInt();
Your function should be like this:
Also you have to pass the value of minLength to function You cannot access minLength outside main.
public static int countWords(String str,int minLength)
{
int count = 0;int c=0;
for (int i=0;i<str.length();i++)
{
if (str.charAt(i) != ' ')
{
if(str.charAt(i)>='a' && str.charAt(i)<='z')
c++;
continue;
}
if(c>=minLength)
{
count++;
}
c=0;
}
if(c>=minLength)
return count+1;
else
return count;
}
}
I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.