Here is my class for finding the amount of spaces, amount of vowels and amount of consonants in a sentence. It works fine but i need it to ignore the cases. How do i do this? I am familiar with the "ignore case" code but im not sure where to put it in this particular program.
public class Counting{
private String sentence;
private int spaces;
private int vowels;
private int consonants;
public Counting(){
sentence = new String();
spaces = 0;
vowels = 0;
consonants = 0;
}
public void setSentence(String sentence){
this.sentence = sentence;
}
public void compute(){
for(int i =0; i < sentence.length();i++){
char letter = sentence.charAt(i);
if(sentence.charAt(i)==' ' ){
spaces++;
}
else if((letter=='a')||(letter=='e')
||(letter=='i')||(letter=='o')||(letter=='u'))
vowels++;
else{
consonants++;
}
}
}
public int getSpaces(){
return spaces;
}
public int getVowels(){
return vowels;
}
public int getConsonants(){
return consonants;
}
}
A common way to do this is to simply convert the original string to all lower case.
Convert the string passed to your class to lower case:
public Counting(){
setSentence("");
spaces = 0;
vowels = 0;
consonants = 0;
}
public void setSentence(String sentence){
this.sentence = sentence.toLowerCase();
}
Use
letter.equalsIgnoreCase("a")
for checks the letter is A or a
It would probably be easier to just maintain a set of all vowels, and consonants and include upper and lower cases - your code as is will include numbers and punctuation as consonants
if (consonents.contains(c)) consonents++;
else if (vowels.contains(c)) vowels++;
else if (spaces.contains(c)) spaces++
alternatively you could keep a map of char and property (an enum starting at 0 and incremented by 1 and including misc as a catch all) and then just keep an array of property counts:
counts[property.get(c)]++;
Put it in your compute() method. This is not very efficient, but it's the simplest thing to do.
public void compute() {
String lowerCaseSentence = sentence.toLowerCase();
//...
}
And replace sentence with lowerCaseSentence in the rest of the code in compute()
Yes, The best way is to convert the whole input sentence into upper case or Lower case and carry out the required operations on it
Try it:
sentence.toLowerCase();
Related
I am trying to write a method which returns the number of times the first character of a string appears throughout the string. This is what I have so far,
public int numberOfFirstChar0(String str) {
char ch = str.charAt(0);
if (str.equals("")) {
return 0;
}
if ((str.substring(0, 1).equals(ch))) {
return 1 + numberOfFirstChar0(str.substring(1));
}
return numberOfFirstChar0(str);
}
however, it does not seem to work (does not return the correct result of how many occurrences there are in the string). Is there anything wrong with the code? Any help is appreciated.
This uses 2 functions, one which is recursive. We obtain the character at the first index and the character array from the String once instead of doing it over and over and concatenating the String. We then use recursion to continue going through the indices of the character array.
Why you would do this I have no idea. A simple for-loop would achieve this in a much easier fashion.
private static int numberOfFirstChar0(String str) {
if (str.isEmpty()) {
return 0;
}
char[] characters = str.toCharArray();
char character = characters[0];
return occurrences(characters, character, 0, 0);
}
private static int occurrences(char[] characters, char character, int index, int occurrences) {
if (index >= characters.length - 1) {
return occurrences;
}
if (characters[index] == character) {
occurrences++;
}
return occurrences(characters, character, ++index, occurrences);
}
Java 8 Solution
private static long occurrencesOfFirst(String input) {
if (input.isEmpty()) {
return 0;
}
char characterAtIndexZero = input.charAt(0);
return input.chars()
.filter(character -> character == characterAtIndexZero)
.count();
}
Here is a simple example of what you are looking for.
Code
public static void main(String args[]) {
//the string we will use to count the occurence of the first character
String countMe = "abcaabbbdc";
//the counter used
int charCount=0;
for(int i = 0;i<countMe.length();i++) {
if(countMe.charAt(i)==countMe.charAt(0)) {
//add to counter
charCount++;
}
}
//print results
System.out.println("The character '"+countMe.charAt(0)+"' appears "+ charCount+ " times");
}
Output
The character 'a' appears 3 times
public class Challenge{
public static String longestWord(String sentence){
String s= sentence;
String[] word=s.split(" ");
String four=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=four.length()){
four=word[i];
}
}
return four;
}
What i'm struggling with here is that if i have the sentence "This has lots that are four long" for example, the code defaults to printing "four" instead of "this" which i need - im not sure how to implement the code which allows me to return the first longest string from a given sentence. Any help would be appreciated.
You just need to stop overwriting your stored “longest word” when the length is equal to the current word. Replacing >= with > in your if statement should do the trick.
Your variable names are confusing, and redundant. I would assume the longest word is the first, and then begin the loop at the second word. And you want > (not >=). Like,
public static String longestWord(String sentence) {
String[] words = sentence.split("\\s+");
String longest = words[0];
for (int i = 1; i < words.length; i++) {
if (words[i].length() > longest.length()) {
longest = words[i];
}
}
return longest;
}
or in Java 8+
public static String longestWord(String sentence) {
return Stream.of(sentence.split("\\s+")).max(
(a, b) -> Integer.compare(a.length(), b.length())).get();
}
You can try in Java 8:
public static String longestString(String sentence){
return Stream.of(sentence.split("\\s+"))
.max(Comparator.comparing(String::length))
.orElse("");
}
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.
I am not very good at java so that's why some things might not make sense at all. I was just simply using code from bits I found online which I know is wrong.
My current issue is that it simply prints a blank code; I am not sure how to get it to print it like so:
Input:
APPLE
Output:
A
AP
APP
APPL
APPLE
Current Code:
import java.util.Scanner;
public class WordGrow
{
public static void main(String[]args)
{
//take your word input
//enter word as a parameter in WordGrow()
System.out.println("Please enter the word to *GROW*");
Scanner scan = new Scanner(System.in);
String theword = scan.next();
System.out.println(makeTree(theword, theword.length()));
}
public static String makeTree(String word, int len)
{
int count = 0;
//start with the first letter and print
//and add another letter each time the loop runs
if (word.length() > 0)
{
for(int i = 0; i < word.length();i++)
{
return word.substring(0, i++);
}
}
return (word.charAt(1) + makeTree(word, len));
}
}
Take Java out of it. Let's take this back to pen and paper.
First, look at the pattern you're printing out. How would you print out just one letter of that string? How would you print out two?
Let's start with that approach. Let's try to print out one letter in that string.
public void printStringChain(String word) {
System.out.println(word.substring(0, 1));
}
What about two letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, 2));
}
What about word.length() letters?
public void printStringChain(String word) {
System.out.println(word.substring(0, word.length()));
}
The main thing I'm trying to get you to see is that there's a pattern here. In order to accomplish this, you likely need to go from zero to the length of your string in order to print out each line on its own.
Here's a start. I leave figuring out the nuance and barriers inside of the substring as an exercise for the reader.
public void printStringChain(String word) {
for (int i = 0; i < word.length(); i++) {
// the question mark relates to i, but in what way?
System.out.println(word.substring(0, (?)));
}
}
If recursion is not compulsory, you could simply iterate through the given String:
String str = "APPLE";
for(int x=0; x<str.length(); x++){
System.out.println(str.substring(0, x+1));
}
Output:
A
AP
APP
APPL
APPLE
One cannot return multiple times, at the first moment the result is passed on to the caller.
For String there is a buffering class for efficiency, the StringBuilder.
Including the empty string that would be:
public static String makeTree(String word) {
StringBuiilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++){
sb.append(word.substring(0, i));
sb.append("\r\n");
}
return sb.toString();
}
It uses the Windows end-of-line characters CR+LF aka \r\n.
You can make that platform independent, but you get the idea.
WITH RECURSION
public static String makeTree(String word)
{
if (word.length() <= 1){
return word;
}
return makeTree(word.subSequence(0, word.length()-1).toString()) + System.lineSeparator() + word;
}
I am working on a pig latin translator which translator the given word into pig latin. Here is the pig latin method and the isVowel method.
public static void pigLatin(String s) {
char[] array = s.trim().toCharArray();
if(isVowel(s.charAt(0)) && !Character.toString(s.charAt(0)).equalsIgnoreCase("y")){
System.out.println(s+"way");
}else {
int i = 0;
String toReturn = "";
do {
toReturn += array[i];
i++;
}while(!isVowel(s.charAt(i)) && !Character.toString(array[i]).equalsIgnoreCase("y"));
System.out.println(s.substring(i)+toReturn+"ay");
}
}
public static boolean isVowel(char c) {
char[] vowels = new char[] {'a','e','i','o','u','y'};
for(int i = 0;i<vowels.length;i++) {
if(Character.toString(vowels[i]).equalsIgnoreCase(Character.toString(c))) {
return true;
}
}
return false;
}
The problem is when I input words "BIrD" and "quiet". First one throws java.lang.StringIndexOutOfBoundsException: String index out of range: 4
The second one doesn't convert properly. Quiet prints uietqay, when it supposes to be ietquay, but that doesn't make sense because, you supposed to take all constants upto the vowel, which should mean uietquay so why is it ietquay? Can someone please point me in the correct direction?
NOTE: This is not homework.
Ignoring case, Is that a "BLRD" or a "bird"? Because if it has no vowels, your do-while loop doesn't terminate except by going out of bounds.
Your second case, "quiet" should be "uietqay" unless you want to add special logic to keep "qu" together. You could accomplish this in your while condition by making it uglier:
while( (!isVowel(s.charAt(i)) || isQU(s, i)) && !Character.toString(array[i]).equalsIgnoreCase("y"))
And then implement the appropriate isQU(String s, int index).
But I'd suggest that a little more rewriting is in order to make your code more readable. As is, I'm not quite sure why your isVowel checks for "y" and your while condition also checks for "y". Some of the time you use array[i] and some of the time you use charAt(i). This inconsistency makes your code harder to read with little or no benefit.
public static String pigLatin(String a){
a=a.toLowerCase();
String [] x=a.split(" ");
int vowl=0;
String c="";
String d="";
String trans="";
for(int i=0; i<x.length; i++){
for(int j = 0;j<x[i].length();j++){
if(x[i].charAt(j)=='a'||x[i].charAt(j)=='e'||x[i].charAt(j)=='i'||x[i].charAt(j)=='o'||x[i].charAt(j)=='u'){
vowl=j;
j=x[i].length();
}
}
c=x[i].substring(0,vowl);
d=x[i].substring(vowl,x[i].length());
trans+= d+c+"ay ";
}
return trans;
}