Print the number of unique vowels in a string, Java - java

I need to find the number of distinct vowels. I came up with the code below but it can't make distinction between same vowels:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}

I would start with five variables (one for each vowel) set to 0, iterate the characters in the input and set the corresponding variable to 1 if I find a match, and simply return the accumulated value of said variables. Like,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}

You could use Set data structure and instead of incrementing the counter just add vowels to the set. At the end you can return just the size of the set.

The problem in your code is that you are not counting the distinct vowels, but all the vowels in the string. A Java-8 way to this:
public static int countDistinctVowels(String str) {
str = str.toLowerCase();
int count = (int) str.chars() // get IntStream of chars
.mapToObj(c -> (char) c) // cast to char
.filter(c -> "aeiou".indexOf(c) > -1) // remove all non-vowels
.distinct() // keep the distinct values
.count(); // count the values
return count;
}
Also use proper Java naming conventions: countDistinctVowels, no count_Distinct_Vowels.

there's definitely an issue here with this counting. at the very least. you should rethink this:
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;

You could use the method contains
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
count += string.contains("a") ? 1 : 0;
count += string.contains("e") ? 1 : 0;
count += string.contains("i") ? 1 : 0;
count += string.contains("o") ? 1 : 0;
count += string.contains("u") ? 1 : 0;
return count;
}

I made explanations in the comments to the code:
public static int count_Vowels(String str) {
str = str.toLowerCase();
Set<Character> setOfUsedChars = new HashSet<>(); // Here you store used vowels
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') { // if currently checked character is vowel...
setOfUsedChars.add(str.charAt(i)); // add this vowel to setOfUsedChars
}
}
return setOfUsedChars.size(); // size of this sets is a number of vowels present in input String
}

static void vow(String input){
String output=input.toLowerCase();
int flaga=0,flage=0,flagi=0,flago=0,flagu=0;
for(int i=0;i<input.length();i++) {
if((output.charAt(i))=='a' && flaga==0) {
System.out.print(input.charAt(i)+" ");
flaga++;
}
if(output.charAt(i)=='e' && flage==0) {
System.out.print(input.charAt(i)+" ");
flage++;
}
if(output.charAt(i)=='i' && flagi==0) {
System.out.print(input.charAt(i)+" ");
flagi++;
}
if(output.charAt(i)=='o' && flago==0) {
System.out.print(input.charAt(i)+" ");
flago++;
}
if(output.charAt(i)=='u' && flagu==0) {
System.out.print(input.charAt(i)+" ");
flagu++;
}
}
}

public static void main(String args[]) {
String sentence;
int v=0,c=0,ws=0;
Scanner sc= new Scanner(System.in);
sentence = sc.nextLine();
sc.close();
sentence.toLowerCase();
String res="";
for(int i=0;i<sentence.length();i++) {
if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'||sentence.charAt(i)=='i'||sentence.charAt(i)=='o'||sentence.charAt(i)=='u') {
if(res.indexOf(sentence.charAt(i))<0) {
res+=sentence.charAt(i);
v++;
}//System.out.println(res.indexOf(sentence.charAt(i)));
}
else if(sentence.charAt(i)==' ')
ws++;
else c++;
}
System.out.println(res);
System.out.println("no of vowels: "+v+"\n"+"no of consonants: "+c+"\n"+"no of
white spaces: "+ws);
}

You can use this Method to Find Count of Distinct vowels.
public static int count_Vowels(String str) {
char[] c = str.toLowerCase().toCharArray();
int Counter=0;
String NewString="";
for(int i=0;i<c.length;i++){
String tempString="";
tempString+=c[i];
if(!NewString.contains(tempString) && (c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')){
Counter++;
NewString+=c[i];
}
}
return Counter;
}

Here is a solve for this problem without using objects. It's a crude but great solve for beginners who encounter this problem with limited js experience.
How to count unique vowels is a string;
function hasUniqueFourVowels(str){
let va = 0
let ve = 0
let vi = 0
let vo = 0
let vu = 0
let sum = 0
for(let i = 0; i < str.length; i++){
let char = str[i];
if(char === "i"){
vi = 1
}
if(char === "e"){
ve = 1
}
if(char === "a"){
va = 1
}
if(char === "o"){
vo = 1
}
if(char === "u"){
vu = 1
}
sum = va + vi + vo + ve + vu
if (sum >= 4){
return true
}
}
return false
}

#Test
public void numfindVoweles(){
String s="aeiouaedtesssiou";
char a[]=s.toCharArray();
HashMap<Character,Integer> hp= new HashMap<Character, Integer>();
for(char ch:a){
if(hp.containsKey(ch) && (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')){
hp.put(ch,hp.get(ch)+1);
}
else if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
hp.put(ch,1);
}
}
System.out.println(hp);
}

Related

String Index Exception

I was trying to convert an expression from infix form to postfix form.I used String a, p , s for stack, postfix result expression, input expression respectively.
Every time I am getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.charAt(String.java:658) at
javaapplication4.A.conversion(A.java:50) at
javaapplication4.A.main(A.java:83)
Please help me how can I solve it.
Here is my code:
import java.util.Scanner;
public class A {
String a="(", s = "", p = "";
int i, n = 1, top = 0, pp = 0;
void push(char ch) {
a = a + ch;
top = n;
n++;
}
void pop() {
n--;
top--;
}
int prio(char ch) {
int f = -1;
if (ch == '(') {
f = 0;
} else if (ch == '+' || ch == '-') {
f = 1;
} else if (ch == '*' || ch == '/' || ch == '%') {
f = 2;
} else if (ch == '^') {
f = 3;
}
return f;
}
void conversion() {
System.out.print("Enter infix form: ");
Scanner sd = new Scanner(System.in);
s = sd.nextLine();
//System.out.println(s);
int t, j, sz;
sz = s.length();
for (i = 0; i < sz; i++) {
if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
p = p + s.charAt(i);
pp++;
} else if (s.charAt(i) == '(') {
push('(');
} else if (s.charAt(i) == '-' || s.charAt(i) == '+' || s.charAt(i) == '*' || s.charAt(i) == '/' || s.charAt(i) == '%' || s.charAt(i) == '^') {
j = prio(s.charAt(i));
t = prio(a.charAt(top));
//System.out.println(t+" "+j);
while (j <= t) {
p = p + a.charAt(top);
pp++;
pop();
t = prio(a.charAt(top));
}
push(s.charAt(i));
} else if (s.charAt(i) == ')') {
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
}
while (a.charAt(top) != '(') {
p = p + a.charAt(top);
pp++;
pop();
}
pop();
}
void postfix() {
System.out.print("postfix form is: ");
System.out.println(p);
}
public static void main(String args[]) {
A h = new A();
h.conversion();
h.postfix();
//System.out.println(h.a);
//System.out.println(h.s);
}
}
Can you confirm if the error is here?
while (a.charAt(top) != '(')
Inside the loop you continuously pop(), which decrements from top, which has the risk of going negative if a match is never found. Even if the error is not here, it should check for that condition.
You may have made an extra pop() definition. Can you check this?

Why subsequence(a,b).toString() is faster than substring(a,b)?

Why subsequence(a,b).toString() is faster than substring(a,b)?
when i convert my all subsequences to substring it slows up to %7 all the time. why does it happen?
Below is my code;
private static String filterStr(String s)
{
for(int a = 0; a < s.length(); a++)
{
int c = s.charAt(a);
if(((c < 65) || ((c >90) &&(c < 97)) || (c > 122)))
{
if(c!=34 && c!=96 && c!=39)// tırnak değillerse
{
String temp = s.substring(0,a);
temp+= s.subSequence(a+1,s.length());
s = temp;
a--;
}
else
{
if(a !=0) // if not at the beginning
{
if(a == s.length()-1)
s = s.subSequence(0,s.length()-1).toString();
else
s = s.subSequence(0,s.length()-2).toString();
}
else
s = s.subSequence(1,s.length()).toString();
}
}
if(c >= 65 && c <= 90) // convert to lower case first character.
{
String temp = s.substring(1,s.length());
c+=32;
s = (char)c + temp;
}
}
return s;
}
CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
this is the implementation of subSequence method, It can not be faster/slower.

ArrayIndexOutOfBounds on enhanced for loop

I am trying to figure out part of an assignment and I have been beating my head against a wall for some time now. I'm trying to transcribe DNA sequences to RNA sequences. I am, however, getting an ArrayOutOfBoundsException. I am new to using enhanced for loops to iterate so my mistake may be hiding in there somewhere. It doesn't occur until the if statement parameters have been met.
private String dnaToRNA(String input) {
StringBuilder b = new StringBuilder();
char[] arr = input.toCharArray();
for (char a : arr) {
if (a == 'T') {
arr[a] ='U';
}
}
for (char a : arr) {
if (a == 'A'){
b.append ('U');
}
else if (a == 'U') {
b.append('A');
}
else if (a == 'C') {
b.append('G');
}
else if (a == 'G') {
b.append('C');
}
}
return b.reverse().toString();
}
}
public void transcribe(int pos1) {
if (pos1 > linkedList.size()) {
System.out.println("Position selected out of range");
return;
}
if (linkedList.get(pos1) != null && isValidDNA(linkedList.get(pos1))) {
linkedList.set(pos1, dnaToRNA(linkedList.get(pos1)));
}
}
The problem is in the statement arr[a] ='U';
The problem is that char is represented as an int internally and 'T' equals 84 hence you get an ArrayIndexOutOfBoundsException.
You need to iterate over it with a traditional counter:
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'T') {
arr[i] ='U';
}
}
You want 1 less than size , so : if (pos1 >= linkedList.size()) {.
When pos1 == linkedList.size() it will be out of bounds

Using replace to take a character and change it to another in java

I am trying to figure out how to remove certain characters to make it English after it being in l33t speak. For example, I 54w 3 5hip5, would translate to I saw 3 ships. I need the 3 to stay a 3 here but in, N3v3r f0rg37 y0|_|r t0w31, I would need the 3's to become e's. Here is my code as follows. All the characters translate over correctly, but I just can't figure out how to do the 3's to e's.
My question is, what is needed to be added to get the 3's to be e's at a certain time, and to have my 3's stay 3's another time. Just so that you know, is that we aren't allowed to use regex, arrays, or string builder for this.
Rules are that if the number is supposed to be a number that it stays a number when you translate it from l33t to English, if the l33t number is a letter than you replace the number and turn it into the letter that corresponds to it.
I also have a different block of code that already takes into consideration the 3 to e's, but instead adds two u's instead of one.
Here are the replacements for the letters, a = 4, b = 8, e = 3, l = 1, o = 0, s = 5, t = 7, u = |_|, z = 2.
I decided to go the route of mike's answer since I understand exactly what's going on.
Thanks to everyone for the help!
Input/Output examples
This following code translates
I 54w 3 5hip5
to
I saw 3 ships
and
3 5hip5 4r3 c0ming m3 w4y
to
3 ships are coming me way
Code
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
boolean threeAtBeginning = false, threeAtEnd = fal;
if (phrase.charAt(0) == '3' && phrase.charAt(1) == ' ')
threeAtBeginning = true;
int length = phrase.length();
if (phrase.charAt(length - 1) == '3' && phrase.charAt(length - 2) == ' ')
threeAtEnd = true;
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if (threeAtBeginning)
finished = '3' + finished.substring(1);
if (threeAtEnd)
finished = finished.substring(0, length - 1) + '3';
return finished;
}
This is clearly homework, and the restrictions are clearly intended to prevent any sane solution, but here's an O(n^2) solution that seems to avoid the restrictions:
public class RemoveL33t {
public static void main(String[] args) {
System.out.println(removeL33t("I 54w 3 5hip5"));
System.out.println(removeL33t("I 54w 33 5hip5"));
System.out.println(removeL33t("I 54w 45 5hip5"));
System.out.println(removeL33t("N3v3r f0rg37 y0|_|r t0w31"));
}
public static String removeL33t(String s) {
String result = "";
for (int pos = 0;;) {
// Find the beginning of the next word.
int whitespaceBegin = pos;
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
// Add the whitespace to the result.
result += s.substring(whitespaceBegin, pos);
// If there is no next word, then we're done.
if (pos >= s.length()) {
return result;
}
// Find the end of the word. Determine if the word is entirely numbers.
int wordBegin = pos;
boolean nonNumber = false;
while (pos < s.length() && !Character.isWhitespace(s.charAt(pos))) {
nonNumber |= s.charAt(pos) < '0' || s.charAt(pos) > '9';
pos++;
}
// Append the word. Perform replacements if it contains a non-number.
if (nonNumber) {
result += s.substring(wordBegin, pos)
.replace('4', 'a')
.replace('8', 'b')
.replace('3', 'e')
.replace('1', 'l')
.replace('0', 'o')
.replace('5', 's')
.replace('7', 't')
.replace("|_|", "u")
.replace('2', 'z');
} else {
result += s.substring(wordBegin, pos);
}
}
}
}
I think this is it.
public static String translateToEnglish(String phrase) {
if (phrase == null) {
return null;
}
String finished = phrase.replace('4', 'a') .replace('1', 'l') .replace('2', 'z') .replace('5', 's') .replace('8', 'b') .replace('0', 'o') .replace('7', 't') .replace("|_|", "u") .replace("3", "e");
finished = finished.replace(" e ", " 3 ");
if(finished.startsWith("e ")){
finished = "3 " + finished.substring(2);
}
if(finished.endsWith(" e")){
finished = finished.substring(0, finished.length()-2) + " 3";
}
return finished;
}
I don't know if this is the answer, but is the best i could think of
public static void main (String[] args) throws java.lang.Exception
{
String c = "I 54w 45 5hip5";
for(String s: c.split(" ")){
try{
Integer.parseInt(s);
System.out.print(s + " ");
}
catch(NumberFormatException e){
s = s.replace('4', 'a').replace('1', 'l').replace('2', 'z').replace('5', 's').replace('8', 'b').replace('0', 'o').replace('7', 't').replace("|_|", "u").replace("3", "e");
System.out.print(s + " ");
}
}
}
This is for your "new" code that you decided to use, or this could just be an alternate solution. The input/output is identical to the samples I gave in my other answer:
public static String translateToEnglish(String phrase) {
if (phrase == null)
return null;
String finished = "";
for (int i = 0; i < phrase.length(); i++) {
char c = phrase.charAt(i);
if (c == '4')
finished += 'a';
else if (c == '3') {
if (i != phrase.length() - 1)
{
if (phrase.charAt(i + 1) == ' ') {
if (i == 0)
finished += c;
else
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
else
finished += 'e';
}
else
{
if (phrase.charAt(i - 1) == ' ')
finished += c;
else
finished += 'e';
}
} else if (c == '1')
finished += 'l';
else if (c == '2')
finished += 'z';
else if (c == '5')
finished += 's';
else if (c == '7')
finished +='t';
else if (c == '8')
finished += 'b';
else if (c == '0')
finished += 'o';
else if (i + 2 < phrase.length() && phrase.charAt(i + 1) == '_' && phrase.charAt(i + 2) == '|') {
finished += 'u';
i += 2;
} else
finished += c;
}
return finished;
}

String errors in convertor

so my code works for some words but not others it sprints out String index out of range: -1
im suppose to print out ub before every vowel and vowel cluster
ex dubious would be dubububious or cat loveo would be lubovudeo
String sentance, set;
sentance = "toster iooppp";
set= translate(sentance);
System.out.println(set);
}
public static String translate (String sentence){
String set = " ";
sentence= sentence.toLowerCase();
scan = new Scanner (sentence);
while (scan.hasNext()) {
set+= toUbbi (scan.next());
set += " ";
}
return set;
}
private static String toUbbi(String word ) {
String str= word;
String new_str="";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isVowel(c) && isVowel(str.charAt(i -1)) )
{ // If is a vowel
new_str += "ub" ;
}
new_str += c;
}
return new_str;
}
private static boolean isVowel(char c)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){
return true;}
return false;
in first iteration it gives error..
if (isVowel(c) && isVowel(str.charAt(i -1)) )
{ // If is a vowel
new_str += "ub" ;
}
so change like this..
if (isVowel(c))
{ // If is a vowel
new_str += "ub" ;
}
or change your loop..
for (int i = 1; i < str.length(); i++) {
// yur remain code...
}

Categories