I am having an error, can someone please help me out. I am trying to print highest occurring vowel in the string.
void vowelCount() {
int countO = 0 ,countU = 0,countI = 0 ,countA = 0 ,countE = 0 ;
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[] {countA,countE,countI,countO ,countU};
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
countA++;
}
if (ch == vowels[1]) {
countE++;
}
if (ch == vowels[2]) {
countI++;
}
if (ch == vowels[3]) {
countO++;
}
if (ch == vowels[4]) {
countU++;
}
}
for( int i = 0; i< vowels.length ; i++) {
if (count[vowels[i]] > maxCount) {
maxCount = count[vowels[i]];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
Arrayindexoutofbound exception results, i am not quite sure where could me my error. Tried for such a long time still the error repeats.
I'd say that count[vowels[i]] is your problem. vowels[i] will not be in the range [0..4] and hence you exceed the bounds of your array. You want count[i] instead. You could try the following simplified code
void vowelCount() {
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[vowels.length];
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
for (int j=0; j<vowels.length; j++) {
if (ch == vowels[j]) {
count[j]++;
break;
}
}
}
for (int i = 0; i<vowels.length; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
The problem is here - if (count[vowels[i]] > maxCount) {
vowels[i] will give you a vowel that is a char. When used as index to fetch from char array, the character gets converted into its ASCII value, which wont be in the range of 0 to 4.
I would say, you should try to find your mistakes, rather than finding a solution. Your following code doesn't do what you expect.
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
countA++;
}
if (ch == vowels[1]) {
countE++;
}
if (ch == vowels[2]) {
countI++;
}
if (ch == vowels[3]) {
countO++;
}
if (ch == vowels[4]) {
countU++;
}
}
When you are updating the variables with countX++, it isn't modifying the values stored in the count[] array, because you already initialised them with 0s i.e. the initial values of countX.
You would get an ArrayIndexOutOfBoundsException, because of these lines:
if (count[vowels[i]] > maxCount) {
maxCount = count[vowels[i]];
maximumChar = vowels[i];
}
Here the vowels[i] is having chars, when you use it as count[vowels[i]] you are using the ascii value of the char stored in the vowels array as an index to access the value in the count array.
In the exception 97 is printed as it is the ascii value of the char 'a'.
You should increment the count array data instead of the variables countO, countU, etc.. variables. You also need to iterate through the count array and find the max number from it and also assign the character from the vowel array to the maximumChar variable.
static String TEXT = "teeaaaiist";
static void vowelCount() {
int countO = 0 ,countU = 0,countI = 0 ,countA = 0 ,countE = 0 ;
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[] {countA,countE,countI,countO ,countU};
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
count[0]++;
}
if (ch == vowels[1]) {
count[1]++;
}
if (ch == vowels[2]) {
count[2]++;
}
if (ch == vowels[3]) {
count[3]++;
}
if (ch == vowels[4]) {
count[4]++;
}
}
for( int i = 0; i< count.length ; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
public static void main(String[] args) {
vowelCount();
}
Related
At a user entered string, I am having a tough time with the counter. The code locates the most occurring character but where can I put counter that it counts the most occurring character. In Java, with the current code please. It's the last method.
import java.util.*;
public class newTest {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter a one line sentence:");
String words = scnr.nextLine();
findAlphabetMode(words);
}
public static void findAlphabetMode(String input){
int[] freq = new int[input.length()];
char mode = input.charAt(0);
boolean noMode = true;
int counter = 0;
int steadyCount = 0;
char string[] = input.toCharArray();
for (int i = 0; i < string.length; i++){
freq[i] = 1;
for(int j = i + 1; j < string.length; j++){
if(string[i] == string[j] && string[i] != ' ' && string[i] != 0){
freq[i]++;
//counter++;
}
if(counter > 1){
if(counter > steadyCount){
steadyCount = counter + 1;
counter = 0;
}
}
if(string[i] == string[j]){
noMode = false;
string[j] = 0;
counter++;
}
}
}
int max = freq[0];
for(int i = 0; i < freq.length; i++){
if(max < freq[i]){
max = freq[i];
mode = string[i];
noMode = false;
}
}
if (noMode) {
System.out.println("Mode: No Mode");
}
else {
System.out.println("The letter " + mode + " occurs " + steadyCount + " times");
}
}
}
`
Must not be that complicated, even without streams:
public static void findAlphabetMode(String input) {
var freq = new int['z'-'a'+1];
for (var ch : input.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
freq[ch-'a'] += 1;
}
}
var max = 0; // index to maximum freq
for (var i = 1; i < freq.length; i++) {
if (freq[i] > freq[max]) {
max = i;
}
}
var ch = (char) ('a' + max);
System.out.printf("found %d times %c%n", freq[max], ch);
}
Not to hard to combine second loop into first loop:
public static void findAlphabetMode(String input) {
var freq = new int['z'-'a'+1];
var max = 0; // index to maximum freq
for (var ch : input.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if (++ freq[ch-'a'] > max) {
max = ch - 'a';
}
}
}
var ch = (char) ('a' + max);
System.out.printf("found %d times %c%n", freq[max], ch);
}
Note: this only counts letters a-z after converting to lower case.
You don't need a nested for loop. That makes your algorithm O(N^2) i.e. when your input string length doubles, the time taken increases fourfold.
You can put each letter in the input string into a Map<Character, Integer>, increasing the value each time you add an existing character, and then at the end find the key with the largest value. A succinct way of doing this is to use streams:
public static void findAlphabetMode(String input) {
input.chars()
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.ifPresentOrElse(
e -> System.out.printf("The letter %c occurs %d times%n", e.getKey(), e.getValue()),
() -> System.out.println("No mode"));
}
If you still prefer loops you can do it like so.
iterate across the string, checking only letters
use map.merge to compute the frequency.
String s =
"To be or not to be, that is the question.";
Map<Character, Integer> map = new HashMap<>();
for (Character c : s.toCharArray()) {
if (Character.isLetter(c)) {
map.merge(c, 1, Integer::sum);
}
}
Now that the frequency is counted, just find the largest
first, make certain characters exist
otherwise, iterate across the entry set finding the maximum value and saving the associated character.
if (map.isEmpty()) {
System.out.println("Mode: No Mode");
} else {
Entry<Character, Integer> result = null;
char chr = ' ';
int count = 0;
for (Entry<Character, Integer> e : map.entrySet()) {
int val = e.getValue();
if (val > count) {
count = val;
chr = e.getKey();
}
}
System.out.printf("The letter `%c` occurs %d times.%n", chr, count );
}
prints
The letter `t` occurs 6 times.
If you want to ignore case, you can do the following in the first loop.
for (Character c : s.toLowerCase().toCharArray()) {
...
}
You don't need to separately increment counter, since you are already calculating frequency for each character, in an array, you can simply loop, over the array and find your maximum occuring character. Here is a simplified version of your code:
import java.util.*;
public class newTest {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter a one line sentence:");
String words = scnr.nextLine();
findAlphabetMode(words);
}
public static void findAlphabetMode(String input){
int[] freq = new int[input.length()];
char mode = input.charAt(0);
char string[] = input.toCharArray();
for (int i = 0; i < string.length; i++){
freq[i] = 1;
for(int j = i + 1; j < string.length; j++){
if(string[i] == string[j]){
freq[i]++;
}
}
}
int max = freq[0];
for(int i = 0; i < freq.length; i++){
if(max < freq[i]) {
max = freq[i];
mode = string[i];
}
}
System.out.println("The letter " + mode + " occurs " + max + " times");
}
}
Take as input S, a string. Write a function that replaces every odd character with the character having just higher ASCII code and every even character with the character having just lower ASCII code. Print the value returned.
package assignments;
import java.util.Scanner;
public class strings_odd_even_char {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
String str = scn.nextLine();
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char)((ch + 1));
System.out.println(ch);
}
for (int j = 1; j < str.length(); j = j + 2) {
char ch = str.charAt(j);
ch = (char)((ch - 1));
System.out.print(ch);
}
}
}
The problem with my code is that it is first printing the values for all the odd characters and then for even characters but what I want is that they get printed in proper sequence like for input --> abcg , the output should be --> badf .
I'd hold the "incremenet" value in a variable and alternate it between +1 and -1 as I go voer the characters:
private static String change(String s) {
StringBuilder sb = new StringBuilder(s.length());
int increment = 1;
for (int i = 0; i < s.length(); ++i) {
sb.append((char)(s.charAt(i) + increment));
increment *= -1;
}
return sb.toString();
}
Just use one loop that handles both characters:
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char) (ch + 1);
System.out.print(ch);
if (i + 1 < str.length()) {
ch = str.charAt(i + 1);
ch = (char) (ch - 1);
System.out.print(ch);
}
}
You only need to iterate one time but do different operation (char+1) or (char-1) depending on the i:
public static void main(String[] args) {
String str = scn.nextLine();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) { // even
ch += 1;
} else { // odd
ch -= 1;
}
System.out.print(ch);
}
}
You are using two loops, but you only need one. You can use the % operator to tell if i is even or odd, and then either subtract or add accordingly:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) {
ch = (char)((ch + 1));
System.out.println(ch);
} else {
ch = (char)((ch - 1));
System.out.print(ch);
}
}
You can do it in one for loop, to do that you will need to check whether the current index is even or odd. if current index is even you will increment char and print, if it is odd you will decrement char and print. to check if even or odd using % operator
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i%2 == 0) {
ch = ch + 1;
System.out.println(ch);
continue;
}
ch = ch - 1;
System.out.println(ch);
}
I would like multiply letter by number in a String and return other String.
I don't know how to concat it when number is higher than 9 and then multiply
eg.
String ="a2b10" convert to String ="aabbbbbbbbbb"
string can have different values: "a2b15", "a16b4c1","a11b14c5"
below I made it only for one letter and one number eg. a1b8, a4b7v3
import javafx.util.converter.CharacterStringConverter;
public class Test {
public static void main(String[] args) {
String txt = "a3b2";
char ch;
for (int i = 0; i < txt.length(); i++) {
ch = txt.charAt(i);
if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
} else if (ch >= '0' && ch <= '9')
{
int count = Character.getNumericValue(ch);
for (int j = 0; j < count; j++) {
System.out.print(txt.charAt(i - 1));
}
} else
System.out.println("not a letter");
}
}
}
In this case it's easier to use regex and group-matching to extract the letter and the number that's following it:
public static void main(String[] args) {
String txt = "a3b10";
String patt = "([a-z])([0-9]*)"; // ([a-z]) will be the first group and ([0-9]*) will be the second
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(txt);
while(matcher.find()) {
String letter = matcher.group(1);
String number = matcher.group(2);
int num = Integer.valueOf(number);
while (num > 0) {
System.out.print(letter);
num--;
}
}
}
OUTPUT
aaabbbbbbbbbb
You can do it like this ...
public class Test {
public static void main(String[] args) {
String txt = "a10b10";
char ch;
char tempChar = ' ';
int temp = -1;
for (int i = 0; i < txt.length(); i++) {
ch = txt.charAt(i);
if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
temp = -1;
tempChar = ch;
} else if (ch >= '0' && ch <= '9') {
int count = Character.getNumericValue(ch);
if (temp != -1) {
count = ((10*temp) - temp);
}
for (int j = 0; j < count; j++) {
//System.out.print(txt.charAt(i - 1));
System.out.print(tempChar);
}
temp = count;
} else {
System.out.println("not a letter");
}
}
}
}
When you're looking for numbers and you find one, keep looking for numbers until you find a letter or the end of the string.
the code should count number of a char array #1 appeared in another char array #2
but it keep adding one more count !!
public static int countSTR(char c1[], int c1Length, char c2[], int c2Length){
int count=0;
char last=c2[c2Length-1];
for (int i=0;i<c1Length;i++)
for (int j=0; j<c2Length;j++)
if (c1[i]==c2[j])
if(j+1==c2Length)
count++;
else
continue;
return count;
}
arrays I tested :
char [] str = {'C','A','B','L','B','Y' ,'A','M','C','S','C'};
char []m={'M','C'};
the output : 3
it should be 1
Please try this:
public static int countSTR(char c1[], int c1Length, char c2[], int c2Length) {
if (c1 == null || c2 == null || c1Length < 1 || c2Length < 1 || c1Length > c1.length || c2Length > c2.length)
return 0;
int count = 0;
for (int i = 0; i <= c1Length - c2Length; i++)
for (int j = 0; j < c2Length; j++)
if (c1[i + j] == c2[j]) {
if (j == c2Length - 1)
count++;
} else
break;
return count;
}
I think you have overcomplicated the process. Just increment the count when they are equal. The for loops will continue, without using continue.
for (int i=0;i<c1Length;i++){
for (int j=0; j<c2Length;j++){
if (c1[i]==c2[j]){
count++;
}
}
}
return count;
You need to only increase the counter if you have a complete match. This should do the job:
private void run() {
char[] text = "foo bar foobar".toCharArray();
char[] searchWord = "foo".toCharArray();
System.out.println(countOccurrences(text, searchWord)); // prints 2
text = new char[] { 'C', 'A', 'B', 'L', 'B', 'Y', 'A', 'M', 'C', 'S', 'C' };
searchWord = new char[] { 'M', 'C' };
System.out.println(countOccurrences(text, searchWord)); // prints 1
}
private int countOccurrences(char text[], char searchWord[]) {
int counter = 0;
for (int offset = 0; offset <= text.length - searchWord.length; offset++) {
if (matchesAt(text, searchWord, offset)) {
counter++;
}
}
return counter;
}
private boolean matchesAt(char[] text, char[] searchWord, int offset) {
for (int i = 0; i < searchWord.length; i++) {
if (text[offset + i] != searchWord[i]) {
return false;
}
}
return true;
}
Here's an alternative using Java 8's stream API:
public static int countSTR(char[] c1, char[] c2)
{
if(c1 == null || c2 == null || c1.length == 0 || c1.length > c2.length)
return 0;
long result = IntStream.range(0, c2.length - c1.length+1)
.mapToObj(i -> IntStream.range(0, c1.length)
.mapToObj(j -> c2[i+j]).toArray())
.filter(array -> IntStream.range(0, c1.length)
.mapToObj(i -> c1[i] == (char)array[i])
.allMatch(bool -> bool == true))
.count();
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(result + " cannot be cast to int without changing its value.");
}
return (int)result;
}
Also, there's no need to pass an int with the length of the arrays as you would in C since you can get an array's length by accessing array.length.
I have a code that must print only vowels from my strings in the array list but I'm not sure if I'm doing it right in my method. How do I resolve this? Its only printing out 5 of them because I'm not sure how to directly get each specific vowels. Please find the below code that I have tried.
import java.util.*;
public class vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
{
number++;
}
}
System.out.println("a count: " +number);
System.out.println("e count: " +number);
System.out.println("i count: " +number);
System.out.println("o count: " +number);
System.out.println("u count: " +number);
}
}
You can do without any loops, quite easily so
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
String arrayToString = vowels.toString();
int length = arrayToString.length();
System.out.println("a count: " + (length - arrayToString.replace("a", "").length()));
System.out.println("e count: " + (length - arrayToString.replace("e", "").length()));
System.out.println("i count: " + (length - arrayToString.replace("i", "").length()));
System.out.println("o count: " + (length - arrayToString.replace("o", "").length()));
System.out.println("u count: " + (length - arrayToString.replace("u", "").length()));
}
It prints
[mitsubishi, subaru, nissan, honda, toyota]
a count: 4
e count: 0
i count: 4
o count: 3
u count: 3
You want to count five types of things, so you need five variables:
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
There are many different ways you could loop through each of the words, and then each of the characters in each of the words. Here's one way:
for (int i = 0; i < vowels.size(); i++) {
String lowerCaseWord = vowels.get(i).toLowerCase(); //get lowercase version so we don't have to check each letter twice
for (int j=0; j<lowerCaseWord.length(); j++){ //loop through each char in the string
char c = lowerCaseWord.charAt(j);
if (c == 'a') aCount++;
else if (c == 'e') eCount++;
else if (c == 'i') iCount++;
else if (c == 'o') oCount++;
else if (c == 'u') uCount++;
}
}
Make 5 different variables to count the number of the vowel. For example numbera, number e etc. Then you will need 5 if statements (one for each vowel) each of which will increase its respective count by 1.
for (int i = 0; i < vowels.size(); i++)
for (int j = 0; j<vowels.get(j).length(); j++) {
if (vowels.get(i).charAt('a'))
{
numbera++;
}
if (vowels.get(i).charAt('e'))
{
numbere++;
}
if (vowels.get(i).charAt('i'))
{
numberi++;
}
if (vowels.get(i).charAt('o'))
{
numbero++;
}
if (vowels.get(i).charAt('u'))
{
numberu++;
}}
This
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
only checks if the string contains a, e, i, o, or u. If it found one of these, it won't bother to check the rest of the string. And since you are using ||, in your if statement, it will not evaluate the next conditions if the current condition is already true, so it will proceed to increment number.
If you want to find the number of each vowel, One way is to loop through the string by turning it into a char array and check if a character is a vowel. Then you should create a counter for each vowel and a separated if/switch statement for each. For example with an if statement.
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
for (int i = 0; i < vowels.size(); i++) {
for (char c : vowels.get(i).toCharArray()) {
if (c == 'a') {
aCount++;
} else if (c == 'e') {
eCount++;
} else (c == 'i') {
iCount++;
} else if (c == 'o') {
oCount++;
} else if (c == 'u') {
uCount++;
} else {
continue;
}
}
}
The following implementation will be efficient. Maintaining a single char array of size 256 would be good enough, which works not only for vowels but for any ASCII character.
import java.util.*;
public class Vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int[] chars = new int[256];
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
for (char c : vowels.get(i).toCharArray()) {
chars[c]++;
}
}
System.out.println("a count: " +chars['a']);
System.out.println("e count: " +chars['e']);
System.out.println("i count: " +chars['i']);
System.out.println("o count: " +chars['o']);
System.out.println("u count: " +chars['u']);
}
}