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
Related
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);
yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:
output example: the string has 8 uppercase letters
the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!
import java.util.Scanner;
public class q36{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a string ");
String input=keyboard.nextLine();
int lengde = input.length();
System.out.println("String: " + input + "\t " + "lengde:"+ lengde);
for(int i=0; i<lengde;i++) {
if(Character.isUpperCase(CharAt(i))){
}
}
}
}
Simply create counters that increment when a lowercase or uppercase letter is found, like so:
for (int k = 0; k < input.length(); k++) {
/**
* The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
* class are static so we use the Class.method() format; the charAt(int index)
* method of the String class is an instance method, so the instance, which,
* in this case, is the variable `input`, needs to be used to call the method.
**/
// Check for uppercase letters.
if (Character.isUpperCase(input.charAt(k))) upperCase++;
// Check for lowercase letters.
if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}
System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);
java 8
private static long countUpperCase(String inputString) {
return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
}
private static long countLowerCase(String inputString) {
return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
}
The solution in Java8:
private static long countUpperCase(String s) {
return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}
private static long countLowerCase(String s) {
return s.codePoints().filter(c-> c>='a' && c<='z').count();
}
You can try the following code :
public class ASCII_Demo
{
public static void main(String[] args)
{
String str = "ONCE UPON a time";
char ch;
int uppercase=0,lowercase=0;
for(int i=0;i<str.length();i++)
{
ch = str.charAt(i);
int asciivalue = (int)ch;
if(asciivalue >=65 && asciivalue <=90){
uppercase++;
}
else if(asciivalue >=97 && asciivalue <=122){
lowercase++;
}
}
System.out.println("No of lowercase letter : " + lowercase);
System.out.println("No of uppercase letter : " + uppercase);
}
}
Use regular expressions:
public Counts count(String str) {
Counts counts = new Counts();
counts.setUpperCases(str.split("(?=[A-Z])").length - 1));
counts.setLowerCases(str.split("(?=[a-z])").length - 1));
return counts;
}
import java.io.*;
import java.util.*;
public class CandidateCode {
public static void main(String args[] ) throws Exception {
int count=0,count2=0,i;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int n = s.length();
for( i=0; i<n;i++){
if(Character.isUpperCase(s.charAt(i)))
count++;
if(Character.isLowerCase(s.charAt(i)))
count2++;
}
System.out.println(count);
System.out.println(count2);
}
}
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, please try to import the least number of libraries. So, avoid using .* as much as you can.
import java.util.Scanner;
public class q36 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a string ");
String input = keyboard.nextLine();
int numberOfUppercaseLetters =
Long.valueOf(input.chars().filter(c -> Character.isUpperCase(c)).count())
.intValue();
int numberOfLowercaseLetters =
Long.valueOf(input.chars().filter(c -> Character.isLowerCase(c)).count())
.intValue();
System.out.println("The lenght of the String is " + input.length()
+ " number of uppercase letters " + numberOfUppercaseLetters
+ " number of lowercase letters " + numberOfLowercaseLetters);
}
}
Sample input:
saveChangesInTheEditor
Sample output:
The lenght of the String is 22 number of uppercase letters 4 number of lowercase letters 18
You simply loop over the content and use the Character features to test it. I use real codepoints, so it supports supplementary characters of Unicode.
When dealing with code points, the index cannot simply be incremented by one, since some code points actually read two characters (aka code units). This is why I use the while and Character.charCount(int cp).
/** Method counts and prints number of lower/uppercase codepoints. */
static void countCharacterClasses(String input) {
int upper = 0;
int lower = 0;
int other = 0;
// index counts from 0 till end of string length
int index = 0;
while(index < input.length()) {
// we get the unicode code point at index
// this is the character at index-th position (but fits only in an int)
int cp = input.codePointAt(index);
// we increment index by 1 or 2, depending if cp fits in single char
index += Character.charCount(cp);
// the type of the codepoint is the character class
int type = Character.getType(cp);
// we care only about the character class for lower & uppercase letters
switch(type) {
case Character.UPPERCASE_LETTER:
upper++;
break;
case Character.LOWERCASE_LETTER:
lower++;
break;
default:
other++;
}
}
System.out.printf("Input has %d upper, %d lower and %d other codepoints%n",
upper, lower, other);
}
For this sample the result will be:
// test with plain letters, numbers and international chars:
countCharacterClasses("AABBÄäoßabc0\uD801\uDC00");
// U+10400 "DESERET CAPITAL LETTER LONG I" is 2 char UTF16: D801 DC00
Input has 6 upper, 6 lower and 1 other codepoints
It count the german sharp-s as lowercase (there is no uppercase variant) and the special supplement codepoint (which is two codeunits/char long) as uppercase. The number will be counted as "other".
Using Character.getType(int cp) instead of Character.isUpperCase() has the advantage that it only needs to look at the code point once for multiple (all) character classes. This can also be used to count all different classes (letters, whitespace, control and all the fancy other unicode classes (TITLECASE_LETTER etc).
For a good background read on why you need to care about codepoints und units, check out: http://www.joelonsoftware.com/articles/Unicode.html
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.
My goal is to create a code that accepts a string, and the minimum number of characters allowed for each word. The output will be an int that tells the users the number of words in their sentence that was above or equal to the min they entered.
Now, my approach to this was to break the sentence up into individual word in the main method, then send each of those words into another method that will count the number of characters.
I am having difficulties in my main method, specifically splitting the sentence into individual words. I want to achieve this without using an array, only loops, substring and indexOf, etc. I commented the section of code that I am having issues with. I tested the rest of my code using a string with only one word, and my letterCounter method seems to be working fine. I know the answer is probably simple, but I am still having trouble figuring it out.
Any help would be wonderful! Thank you!
Here is my code:
public class Counter
{
public static void main(String [] args)
{
int finalcount = 0;
System.out.print("Enter your string: ");
String userSentence = IO.readString();
System.out.print("Enter the minimum word length: ");
int min = IO.readInt();
//Error checking for a min less than 1
while(min < 0)
{
IO.reportBadInput();
System.out.print("Enter the minimum word length: ");
min = IO.readInt();
}
int length = userSentence.length(); // this will get the length of the string
for(int i = 0; i < length; i ++)
{
if (userSentence.charAt(i) == ' ')
{
/* I dont know what to put here to split the words!
once I split the userSentence and store the split word into
a variable called word, i would continue with this code: */
if((letterCounter(word)) >= min)
finalcount++;
else
finalcount = finalcount;
}
}
IO.outputIntAnswer(finalcount);
}
//this method counts the number of letters in each word
public static int letterCounter (String n)
int length = n.length();
int lettercount= 0;
for(int i = 0; i < length; i ++)
{
boolean isLetter = Character.isLetter(n.charAt(i));
if (isLetter)
{
if ((n.length()) >= length)
{
lettercount++;
}
}
}
return lettercount;
}
}
Have a a look at String.split()
You could use string.split() like this to accomplish this:
String [] splittedString = inputString.split(" ");
for(int i = 0;i< splittedString.length; i++){
String currentWord = splittedString[i];
if(currentWord.length() >= min){
finalcount++;
}
}
This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");
I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}