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();
Related
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.
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;
}
}
I'm working on the vowel counting problem at coedabbey, but my solution doesn't seem to be working. Here's what I'm doing:
import java.util.Scanner;
public class Solution {
private static Scanner input;
public static void main(final String[] args){
input = new Scanner(System.in);
int amount = input.nextInt();
for(int i = 0 ; i < amount ; i++){
int sum = 0;
String nowa = input.nextLine();
for(int j = 0; j < nowa.length() ; j++){
char x = nowa.charAt(j);
if(x == 'a' || x == 'o' || x == 'u' || x == 'i' || x == 'e' || x == 'y'){
++sum;
}
}
System.out.println(sum+ " ");
}
}
}
But it does not do the right number of lines, and always outputs 0 for the count for a line after I enter the input. After that it does one fewer line than I expected.
An example run might look as follows:
> java Solution
> 3
0
> hello
2
> george
3
But, I wanted to enter another line because I said "3" at the beginning.
Skip a line after nextInt() as it doesnt consumes whole line it consumes only token
int amount = input.nextInt();
input.nextLine();
Demo
Instead of String nowa = input.nextLine(); try String nowa = input.next();.
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++)
for my compsci assignment we're supposed to take a string given to us with integers and letters in it, then create a method that takes that string and converts it into an integer array with the integers in it. For some reason my method is not adding ints to the array, I'm not sure why.
For the LETTERS given in the string, we're supposed to discard them, so we have an array with ONLY int values; ex. input: abs3131afas312 the array would have {3131,312}
This is the link to the assignment.
Here's my method:
public static int[] intParse(String a){
int[] array1 = new int[a.length()];
int b = 0;
for(int i = 0; i < a.length(); ++i)
{
int g = a.charAt(i);
if(g == 1 || g == 2 || g == 3 || g == 4 || g == 5 || g == 6 || g == 7 || g == 8 || g == 9 || g == 0)
{
String c;
for(int j = i; j < a.length(); ++j)
{
int k = a.charAt(j);
if(k != 1 && k != 2 && k != 3 && k != 4 && k != 5 && k != 6 && k != 7 && k != 8 && k != 9 && k != 0)
{
c = a.substring(j,k-1);
array1[b] += Integer.parseInt(c);
b++;
j = (a.length());
i = a.charAt(j);
}
else
{
c = a.substring(j,a.length());
array1[b] = Integer.parseInt(c);
j = a.length();
}
}
}
}
return array1;
}
Rather than comparing your characters to integers and using Integer.parseInt, you should be using the following very useful utility methods:
Character.isDigit(int codepoint)
Character.getNumericValue(int codepoint)
Also, your logic seems a little sketchy. When k is a digit code point, you are trying to parse the entire rest of the string. That doesn't seem consistent with what you're trying to do with the outer loop.
First of all, a is a string, and contains ASCII characters not integers. Character '1' is not equal to the integer 1. It is equal to the ASCII value of '1' which happens to be 49.
So first thing you should do is change that long if condition to:
char c = a.charAt(i);
if (c >= '0' && c <='9')
{
...
}
What you should do then is keep a string (a new string each time you encounter a non-numeric character and then a numeric character, and keep appending c to it until the character you find is non-numeric.
Then you can simply do Integer.parseInt(yourString) to get the number in an integer.
a fix for you:
char g = a.charAt(i);
if(g == '1' || g == '2' || g == '3' || g == '4' || g == '5' || g == '6' || g == '7' || g == '8' || g == '9' || g == '0') {
or much nicer:
char g = a.charAt(i);
if(g >= '0' && g <= '9') {
Your other if needs to be fixed, too
char k = a.charAt(j);
if(k < '0' || k > '9') {
You might prefer this approach:
Scanner sc = new Scanner("abs3131afas312");
String match;
while ((match = sc.findInLine("(\\d+)"))!=null) {
// instead of printing it, put it in your array
// or a list (and then convert to array)
System.out.println(Integer.parseInt(match));
}
sc.close();
Output:
3131
312