'o' and last vowel in user input are not found - java

My program is suppose to check one word per line for vowels; however It does not count the the vowel if it is the last letter in the word or if the vowel is 'o' I have been staring at this for hours. Any help would be great.
import java.util.*;
public class Vowel
{
public static void main(String[] args)
{
String word;
int len;
int position;
int vowelCount;
char ch;
Scanner kbd = new Scanner(System.in);
word = kbd.next();
while (!word.equals("the_end"))
{
len = word.length() - 1;
vowelCount = 0;
for (position = 0; position < len-1; position++)
{
ch = word.charAt(position);
if ((ch == 'a') || (ch == 'e') || (ch == 'i')
|| (ch == 'o') || (ch == 'u')) vowelCount++;
}
System.out.print("There ");
if (vowelCount == 1) System.out.print ("is 1 vowel in ");
else System.out.print("are " + vowelCount + " vowels in ");
System.out.println(word);
word = kbd.next();
}
}
}
I'm now trying with
for (position = 0; position < word.length(); position++)

Suppose you have a six-letter word, "kitten". The first character position is 0, so you want position in your loop to take on the values, 0, 1, 2, 3, 4, and 5.
What your code actually does:
len = word.length()-1;
This sets len to 5.
for (position = 0; position < len-1; position++)
Since len-1 is 4, this will only run the loop as long as position < 4. That is, as soon as position reaches 4, it exits (since 4 < 4 is false). So position will only take on the values 0, 1, 2, 3. That is, you'll be off by 2.
Getting rid of both -1s in the above code will eliminate the problem.

for (position = 0; position < len-1; position++)
^^^^^^^^
You are stopping your loop before the end of the string.
Also, if you're assigning len to word.length()-1, you're chopping off a letter that way too. Better just to write:
for (position = 0; position < word.length(); position++)
I don't know why it would be missing the letter 'o', but you might want to check if you need to convert your string to lower case. Currently, if your vowels are capitals, they won't be counted.
You could do this by putting:
word = word.toLowerCase();
before your for loop.

You seem to want to iterate over the whole String, but you have
len = word.length()-1;
...
for (position = 0; position < len-1; position++)
// ^^^ why?
You're making your String 2 characters shorter. Don't do that.
for (position = 0; position < word.length(); position++)

Related

Counting vowels in strings in java doesn't count the first string

Here is the code I wrote in Java to count vowels (a, e, i, o, u, y) in n strings:
import java.util.*;
import java.io.*;
public class VowelCount {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
int counter = 0;
for(int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'y' || ch == 'Y') {
counter += 1;
}
}
count[i] = counter;
}
}
for(int k = 0; k < n; k++) {
System.out.print(count[k] + " ");
}
}
}
If I insert 10 strings like:
(hello, hi, string, int, double, boo, ad, ok, def, rep)
it should return
2 1 1 1 3 2 1 1 1 1
but what it returns is
0 2 1 1 1 3 2 1 1 1
so it count the first one as the second and doesn't count the last one (in fact right after writing "def" in the console it runs the code and prints the solution in console.
Can you help me figure it out where I am wrong? It would be really appreciated, thanks!
This looks like standard hackerrank format. I believe most of the templates include code to read the data - if one problem doesn't, just copy code from one that does.
I'm guess the problem here is that nextInt does not read the line ending. The first nextLine just reads the newline after the count.
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
The method .nextInt() doesn't finish to read all the line, so your first call to x.nextLine() catch the space after the int.
Just add a line after : x.nextLine();
int n = x.nextInt();
int[] count = new int[n];
x.nextLine();

How to fix: Number of occurrences of a letter in a string

I'm trying to count the number of occurrences of letters that are in string. The code that I have written technically does what I want, but not the way I want to do it. For example, if I input "Hello World", I want my code to return "a=0 b=0 c=0 d=0 e=1 etc...." with the code I have written it returns "H=1, e=1, l=2 etc...."
Also how would I make sure that it is not case sensitive and it doesn't count spaces.
Code:
import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++)
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}
As I hinted in my original comment you only need an array of 26 int(s) because there are only 26 letters in the alphabet. Before I share the code, it is important to note that Java char is an integral type (and, for example, 'a' + 1 == 'b'). That property is important, because it allows you to determine the correct offset in an array (especially if you force the input to lower case). Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();
If you really want to see all of the letters that have counts of zero (seems pointless to me), change
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
to remove the if and just
System.out.printf("%c=%d ", 'a' + i, count[i]);
Change str = scan.nextLine(); to str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase() is a method which makes every char in the string lowercase.
.replaceAll() is a method which replaces one char with another. In this case, it replaces whitespaces with nothing.

Occurrences in char Array

I have this problem,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Exercise_12_2.main(Exercise_12_2.java:28)
When i am trying to just simply count the occurrences of the letters in a char array. I just cant seem to wrap my head around how to work it out. I have been at it for several hours. Please help get me on the right track.
input: a a a b b c !
Expected output:
Counts:
a 3
b 2
c 1
This is my code so far. Please help me.
import java.util.Scanner;
public class Exercise_12_2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); // Setup scanner
char[] charArray = new char[100];
int[] counts = new int[26];
char tempinput = '?';
System.out.print("Enter letters (or ! to quit): ");
while (tempinput != '!')
{
tempinput = (input.next()).charAt(0);
charArray[tempinput]++;
for (int c = 'a'; c <= 'z'; c++)
{
for (int k = 0; k <= charArray.length; k++)
{
if (c == charArray[k])
{
counts[c] += 1;
}
}
}
}
}
public static void displayCounts(int[] counts)
{
for (int i = 0; i < counts.length; i++)
{
if ((i + 1) % 10 == 0)
{
System.out.println(counts[i] + " " + (char)(i + 'a'));
}
else
{
System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
}
}
}
}
java.lang.ArrayIndexOutOfBoundsException: 100 means you are asking for the 101st element of an array with only 100 elements. Remember, java arrays are indexed starting with 0.
From that you might be able to tell why this line is broken:
for (int k = 0; k <= charArray.length; k++)
charArray.length is 100, so you run up until k is 101, meaning that you try charArray[100] which is asking for the 101st element of charArray, but charArray only has 100 elements.
If you switch k <= charArray.length to k < charArray.length you should get farther.
On an unrelated note, counts[c] += 1; won't work. The int val of a char is its ascii value. The letter a for example is 97, so you'll go way off the end of your counts array. This also doesn't account for upper/lower case (which have different numeric values).
This problem becomes much easier if you use an appropriate data structure. For example, I would use a Map<Character, Integer> to keep the count and then iterate that to display. Like,
Scanner input = new Scanner(System.in); // Setup scanner
System.out.print("Enter letters (or ! to quit): ");
Map<Character, Integer> map = new HashMap<>();
char ch;
while ((ch = Character.toLowerCase(input.next().charAt(0))) != '!') {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
System.out.println("Counts:");
for (int c = 'a'; c <= 'z'; c++) {
if (map.containsKey((char) c)) {
System.out.printf("%c\t%d%n", c, map.get((char) c));
}
}
Which I tested with your example input, and I get as requested:
Enter letters (or ! to quit): a a a b b c !
Counts:
a 3
b 2
c 1
I think after creating the character array of [a, a, b c, d, !, ..], following code will be enough to calculate count for each alphabet [a-z].
for (int k = 0; k < charArray.length; k++)
{
char c = charArray[k];
if (c >= 'a' && c <= 'z' )
{
counts[c - 'a'] += 1;
}
}

My for-loop is iterating by two

I'm trying to make a program that counts the number of vowels in a sentence, but for some reason my for-loop keeps iterating by 2 (figured this out by printing out the value of i during each iteration). What's wrong with it?
//input
Scanner input = new Scanner(System.in);
String sentence;
//prompt
System.out.print("Type a sentence. \nThe number of vowels will be counted.");
sentence = input.nextLine();
//vowel check
int charcount = 0;
String temp;
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i++);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
System.out.print("There are " + charcount + " vowels in your sentence.");
}
}
Change this line to:
temp = sentence.substring(i, i+1);
If you do i++ it will increment the value of i.
i++ is equivalent to i = i + 1;
There are two times when you're incrementing i , once in your for loop definition, and once in your sentence.substring
Any time you put i++ the variable i will be increased by 1, regardless of it being in the for loop's definition or in another part of the loop.
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") == true)
charcount ++;
else if (temp.equalsIgnoreCase("e") == true)
charcount ++;
else if (temp.equalsIgnoreCase("i") == true)
charcount ++;
else if (temp.equalsIgnoreCase("o") == true)
charcount ++;
else if (temp.equalsIgnoreCase("u") == true)
charcount ++;
}
Should work.
Also, and someone who is more familiar with java than I am can correct me on this if I'm mistaken, but temp.equalsIgnoreCase() returns a boolean, so you don't need to do == True, you can just write else if (temp.equalsIgnoreCase("u"))
Addition: As per Scary Wombat's comment, you could simplify this even more so, as so:
for(int i = 0; i < sentence.length(); i++)
{
temp = sentence.substring(i, i+1);
if (temp.equalsIgnoreCase("a") || temp.equalsIgnoreCase("e") ||
temp.equalsIgnoreCase("i") || temp.equalsIgnoreCase("o") ||
temp.equalsIgnoreCase("u"))
charcount ++;
}
You have two instances of i++. Each is equivalent to i=i+1. You probably want your second one to be (i+1) rather than i++.
I suggest you don't use the substring method as it creates a new string from the original string.
From the documentation:
String substring(int beginIndex)
Returns a new string that is a substring of this string.
Instead, use the charAt method which returns the character value at the specified index.
You can also cleanup the implementation by using a string with the vowels and invoking the indexOf method on it to test if the character in question is a vowel or not. Below is an example:
String vowels = "aeiou";
sentence = sentence.toLowerCase();
for (int i = 0; i < sentence.length(); i++) {
char letter = sentence.charAt(i);
if (vowels.indexOf(letter) > -1) {
charCount++;
}
}

Solution with CCC 2015?

I'm trying to #2 of the Canadian Computing Contest, but my solution doesn't work. It only reads the first few characters(the first three I believe) and just ends the loop, then proceeding to provide the adequate output based only on the first three characters.
Here is the past paper:http://cemc.uwaterloo.ca/contests/computing/2015/stage%201/juniorEn.pdf
My code
Scanner input = new Scanner(System.in);
String lines = input.next();
char[] line = lines.toCharArray();
int happy = 0;
int sad = 0;
int i = 0;
while(i < line.length)
{
if(line[i] == ':' && line[i+1] == '-')
{
if(line[i+2] == ')')
happy++;
else if(line[i+2] == '(')
sad++;
i+=3;
}
else i++;
}
if(happy == 0 && sad == 0)
System.out.print("none");
else if(happy == sad)
System.out.print("unsure");
else if(happy>sad)
System.out.print("happy");
else if (sad>happy)
System.out.print("sad");
consider that with
while(i < line.length)
if i == line.length - 1
then if you do
line[i+1]
you will exceeed the length or your array and get an OutOfBoundsException

Categories