Java: Number of vowel in a string - java

I was asked to write a class NumberOcc with these methods:
-method getNbOcc which takes as arguments a string str and a character 'c' and return the number of occurence of the character 'c'.
-method dspNbOcc which displays the value returned by getNbOcc
-method getNbVoy which returns the number of vowel inside a string str
-method dspNbVoy which displays the value returned by getNbVoy
The problem is the value returned by getNbVoy is wrong, example: for str=stackexchange it returns 34 vowels.
public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
for(int i=0;i<str.length();i++) {
if (str.charAt(i)==c)
count1++;}
return count1;
}
public static void dspNbOcc() {
System.out.println(count1);
}
public static int getNbVoy(String str) {
String vowel="aeiouy";
for(int j=0;j<vowel.length();j++) {
count2+=getNbOcc(str,vowel.charAt(j));}
return count2;
}
public static void dspNbVoy() {
System.out.println(count2);
}
}
TestClass
public class TestNumberOcc {
public static void main(String[] args) {
String str="stackexchange";
NumberOcc.getNbOcc(str, 'e');
NumberOcc.dspNbOcc();
NumberOcc.getNbVoy(str);
NumberOcc.dspNbVoy();
}
}
Thanks for helping

Remove the static fields, pass the values to the methods. And use them to display the results. Like,
public static int getNbOcc(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
public static void dspNbOcc(String str, char c) {
System.out.println(getNbOcc(str, c));
}
public static int getNbVoy(String str) {
int count = 0;
char[] vowels = "aeiouy".toCharArray();
for (char ch : vowels) {
count += getNbOcc(str.toLowerCase(), ch);
}
return count;
}
public static void dspNbVoy(String str) {
System.out.println(getNbVoy(str));
}
And then testing everything is as simple as
public static void main(String[] args) {
String str = "stackexchange";
NumberOcc.dspNbOcc(str, 'e');
NumberOcc.dspNbVoy(str);
}

the issue is you're not initializing your count1 (nor count2, but that bug doesn't affect anything in this case) at the beginning of your count method... add this line to the beginning of your getNbOcc method before the loop:
public static int getNbOcc(String str, char c) {
count1 = 0; // add this line
for(int i=0;i<str.length();i++) {

The solution is to apply what you did in your countLetterInString function to countVowelsInString. Just remember to use local variables. You will run into issues with static/global variables if the function is called more than once, but local variables will work the same way every time.
public static int countVowelsInString(String str) {
String vowels = "aeiouy";
// Move counter into the function
int numVowels = 0;
for(int j = 0;j<vowel.length();j++) {
numVowels += getNbOcc(str, vowel.charAt(j));
}
return numVowels;
}

Related

All combination of string char

I have string and i need to print all the combination of the string Char's
Example
For the string "123" the output is:
1,2,3,12,13,21,23,31,32,123,132,213,231,312,321
It must be without loops, only with recursion.
Thanks!
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
I think just giving you the full code would be a little to easy for you. This is the simple set up for the code that you would want. The recurse method is not completely finished, the return statement being one of the things that you will need to fix first. By answer the question, this way, I hope that I am still answering the question, but also still allowing you to fully learn and understand recursion on your one. By the way,
for the public static void main(String [] args) part
You would also put that in a separate class like so:
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public class CharacterRecursionClient
{
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
That would work just as well if you are required to have a client class. I hope that this help and cleared up at least a couple of things.

swapping of numbers using index in java is not working

package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}

Heap Sort. What's wrong in this code?

I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.

Searching through Objects Issue

The program is to find all of the words in a text file and count how many times each word is found. Our definition of a "word" will be relatively crude and will be done by splitting the line based on characters that are not alphabetic. I know there are easier ways to go about this but we were required to use a class and a search method like the one I attempted. I can't figure out why it's not incrementing word's that are already in wordList. I believe it's either completely skipping over my if (foundAt >=0, or it's not incrementing it correctly, I'm leaning toward my search method being wrong, but I can't figure out the problem. Any and all help is much appreciated, thanks for your time.
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
int n=0;
WordCount[] wordList= new WordCount[10000];
Scanner words = new Scanner(new File("input.txt"));
while (words.hasNextLine() && n < 10000)
{
String line = words.nextLine();
String[] tokens = line.split("[^\\p{Alpha}]");
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].length()>0)
{
WordCount word = new WordCount(tokens[i]);
int foundAt = search(wordList, word, n);
if (foundAt >= 0)
{
wordList[foundAt].increment();
}
else
{
wordList[n]=word;
n++;
}
}
}
}
//Arrays.sort(wordList);
String alphabeticFileName = "alphabetic.txt";
String frequencyFilename = "frequency.txt";
PrintWriter output = new PrintWriter(alphabeticFileName);
for (int i=0; i<n;i++)
{
output.println(wordList[i].toString());
}
output.close();
//Sort on frequency somehow
PrintWriter output2 = new PrintWriter(frequencyFilename);
for (int i=0; i < n; i++)
{
output2.println(wordList[i].toString());
}
output2.close();
}
public static int search(WordCount[] list,WordCount word, int n)
{
int result = -1;
int i=0;
while (result < 0 && i < n)
{
if (word.equals(list[i]))
{
result = i;
}
i++;
}
return result;
}
}
class WordCount
{
String word;
int count;
static boolean compareByWord;
public WordCount(String aWord)
{
setWord(aWord);
count = 1;
}
private void setWord(String theWord)
{
word=theWord;
}
public void increment()
{
count=+1;
}
public static void sortByWord()
{
compareByWord = true;
}
public static void sortByCount()
{
compareByWord = false;
}
public String toString()
{
String result = String.format("%s (%d)",word, count);
return result;
}
}
Output:
Peter (1)
Piper (1)
picked (1)
a (1)
peck (1)
of (1)
pickled (1)
peppers (1)
A (1)
peck (1)
of (1)
pickled (1)
peppers (1)
Your increment function is wrong. You've written:
count =+1;
Which only sets the count to one. To increment count by one you put:
count += 1;

Recreate valueOf(double d) in Java's String class

I made an object, MyString. I can't figure out how to recreate valueOf(double d). I recreated valueOf for integers. Just to make it easier I limited the amount of decimal places to 8. How can I recreate valueOf(double d)?
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
int digits = (int)(Math.log10(i)+1);
char[] b = new char[digits];
for (int j = 0; j < digits; j++) {
b[j] = (char) (48 + i / 10);
i = i % 10;
if (i < 10) {
b[j + 1] = (char)(48 + i);
break;
}
}
MyString ms = new MyString(b);
return ms;
}
public static MyString valueOf(double d) {
char[] d1 = new char[digits];
//Take each digit of the number and enter it into the array
MyString ms = new MyString(d1);
return ms;
}
public static void main(String[] args) {
}
}
I assume you are doing this for fun... so here is the approach I took. You have valueOf(int i) already, so why not basically reuse that function. Just take the double and keep multiplying it by 10 until you have an int. Keep track of where the decimal place goes, then you basically call your valueOf(int i) but also include the decimal point.
I had trouble running your code so I re-did valueOf(int i) then created valueOf(int i, int decimalSpot), passing in -1 or 0 for the decimal spot then it's an integer value and don't use a decimal place.
Anyway, here is what I came up with. It's late, so probably not the cleanest code, but should give you a proof of concept.
public class MyString {
private char[] a;
public MyString(String s) {
this.a = s.toCharArray();
}
public MyString(char[] a) {
this.a = a;
}
public String toString() {
return new String(a);
}
public int length() {
return a.length;
}
public char charAt(int i) {
return a[i];
}
public static MyString valueOf(int i) {
return MyString.valueOf(i,-1);
}
public static MyString valueOf(double d) {
int decimalPlace = 0;
while (d != (int)d)
{
decimalPlace++;
d = d*10;
}
return MyString.valueOf((int)d,decimalPlace);
}
public static MyString valueOf(int i, int decimalSpot) {
int index=0;
int digits = (int)(Math.log10(i)+1);
int stringLength=digits;
if (decimalSpot == 0) decimalSpot=-1; // Don't return 1234. - just return 1234
if (decimalSpot != -1)
{
// Include an extra spot for the decimal
stringLength++;
}
char[] b = new char[stringLength];
for (int j = digits-1; j >= 0; j--) {
int power = (int) Math.pow(10,j);
int singleDigit = (int) Math.floor(i/power);
i = i - power*singleDigit;
b[index++] = (char) (48 + singleDigit);
if (decimalSpot==j)
{
b[index++] = '.';
}
}
MyString ms = new MyString(b);
return ms;
}
public static void main(String[] args) {
MyString ms = MyString.valueOf(12345);
System.out.println(ms);
ms = MyString.valueOf(12345.12313);
System.out.println(ms);
}
}
Rather than trying to solve this problem for every possible source datatype you should be just concentrating on constructing your class from a String. Then all you have to do is delegate this method and all the others you haven't done yet to the corresponding String method in each case, take the resulting String, and construct your object with that String.

Categories

Resources