Jave beginner - count number of words in a string [duplicate] - java

This question already has answers here:
Scanner only reads first word instead of line
(5 answers)
Closed 2 years ago.
I'm trying to write code that receives a string as input and then counts the number of words within said string, but it returns 1 no matter the input. Surprisingly, pasting the sample code from my textbook (C. Thomas Wu - An Introduction to Object-Oriented Programming) gives the same problem and I can't figure out why.
My code is as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scanner.next();
char BLANK = ' ';
int index = 0, wordCount = 0;
int numberOfCharacters = sentence.length();
while (index < sentence.length()){
while (index < sentence.length() && sentence.charAt(index) != BLANK){
index++;
}
while (index < sentence.length() && sentence.charAt(index) == BLANK){
index++;
}
wordCount++;
}
System.out.println(wordCount);
}
}
Thanks in advance for any help!

You have used scanner.next() which will capture only the first word of the sentence. It stops where it finds a white space. You need to use scanner.nextLine().
Also, given below is another way of doing it:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
System.out.println("Total no. of words: " + scanner.nextLine().split("\\s+").length);
}
}
A sample run:
Enter a sentence: Ram is a good boy.
Total no. of words: 5
Another sample run:
Enter a sentence: Harry is an intelligent guy.
Total no. of words: 5
In this program, we are splitting the input on space(s) using String::split function, which returns a String[] with the words of the input as its elements, and then we are printing the length of this resulting String[].

Scanner.next returns only a single "word" (for some definition of word), and every time you call it will return the next word in the input.
To get an entire line of text, with multiple words, use nextLine:
String sentence = scanner.nextLine();

Hello you can do this by using sentence.split(' ') and getting the length.
For an example:
String sentence = "I like eating apples everyday";
String[] words = sentence.split(' ');
int wordCount = words.length;

Code to check count number of words in a string:
String sentence = "I'm new user of Java!";
int word_count = 0;
for (int i = 1; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
char ch2 = sentence.charAt(i-1);
if (ch == ' ' && ch2 != ' ')
word_count++;
}
System.out.println("Word count: " + word_count);
out:
Word count: 4
java code at online compilier

You can use regex to count all types of spaces including more than 1 successive space characters, tabs & line returns:
\\s is a regex that matches space characters
.split(): split the string into different strings based on a separator/delimiter which is the \\s+ regex
String sentence = scanner.next();
String[] split= sentence.split("\\s+");
int wordCount = split.length;
System.out.println(wordCount);

Related

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
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.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

error in my Java

So currently im trying to do a java project and have seen a few answers on this on other websites but im having trouble understandign them. i need to do this:
"Write a program that prompts the user to input a string of words, then counts and displays the number of times each letter in the alphabet appears in the string. It is not necessary to distinguish between uppercase and lowercase letters. Your output should be formatted as follows:
Letter A count = xx
Letter B count = xx
....
Letter Z count = xx"
and this is what I have so far:
import java.util.Scanner;
public class Unit9 {
public static void main(String [] args )
{
int array[] = new int[26];
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
Scanner Keyboard = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string.");
userInput = Keyboard.next().toLowerCase();
for (int i = 0; i < userInput.length(); i++)
{
char ch = userInput.charAt(i);
if (ch >= 'a' && ch <= 'z') {
array[ch - 'a'] ++;
}
}
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + array[ch-'a']);
}
}
}
but when i enter "hello" (without the quotes) i end up getting this:
Please enter a string.
hello
979899100102102103105105106107110109110112112113114115116117118119120121122
what is happening? what am i doing wrong?
EDIT: actually, i just realized something else... it stops detecting when there is a space in the user input meaning that it only detects the first word. how would I add detection for a space as well?
The reason why it only detected the first word is because you entered:
userInput = Keyboard.next().toLowerCase();
instead of
userInput = Keyboard.nextLine().toLowerCase();
nextLine() reads the whole line entered while next() only reads the first word.
You are using the + operator between a char and an int on this line:
System.out.print(ch + array[ch-'a']);
This gives you a number as a result, which is then inputted into System.out.print taking int as input, therefor printing the number itself. You also have no spacing (or use println), so it appears to be one long line of numbers.
Try this for your last loop:
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + ": "+ array[ch-'a']+" ");
}
It will now no longer be seen as addition, but rather concatination and show as a string of "letter: amount", one after another for the entire alphabet.

String Array for Java

I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");

Count the occurences of a letter in a string [duplicate]

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 9 years ago.
I updated my code from previous suggestions, and it is only reading the first word in my sentence, any suggestions on how to get it to read the whole sentence? (I have to use a for loop)
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count ++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
Output:
Enter a character for which to search
h
Enter the string to search
hello how are you
There are 1 occurrences of h in hello
It's a little tricky here. You will need two readLines().
System.out.println("Enter a character for which to search");
letter = in.nextLine().charAt(0);
System.out.println("Enter the string to search");
sentence = in.nextLine();
Scanner.next() only reads one word and does not finish the line.
// Assume input: "foo" [enter] "test this yourself!"
Scanner.next(); // "foo"
Scanner.nextLine(); // EMPTY STRING!
Scanner.nextLine(); // "test this yourself!"
Your scanner only reads the next word (in.next()). If you want to read a whole line, you should use the method nextLine of your Scanner.
If you expect the user to input several values, you will have to read accordingly from that Scanner (so you will also have to read the newline from the answer of the first question you are asking the user).
I will not give you code to fix the issue, this is just meant as a pointer in the right direction. It would be very good if you familiarize yourself with those standard classes. Sun/Oracle have done a very good job in documentation. So the first look should always be in the Java Doc of the classes you are using.
Here is the doc for the class Scanner.

What's wrong with my Java code? It should count the spaces, but returns 0

The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.
I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.
From the docs for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Use nextLine instead. You can also print the line for debugging:
System.out.println(str);
Use String str = input.nextLine(); instead of String str = input.next();
This is the way you should do to get the next string.
You could have checked that str has the wrong value.

Categories