How do you use charAt with an array? - java

i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.

You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}

The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.

public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1

Related

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

Write method countVowels to take a string and return the amount of vowels

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("Number of Vowels in the string: " + countVowels(str)+"\n");
}
public String countVowels(String count) {
}
sorry but im very new to java and coding and trying to find a way to create a vowel counter but I seem to struggle with creating one ive tried looking up many answers but cant find one.
Try something like this:
public int countVowels(String str)
{
int vowelCount = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.toLowerCase().toCharArray()[i] == 'a' | str.toLowerCase().toCharArray()[i] == 'e' | str.toLowerCase().toCharArray()[i] == 'i' | str.toLowerCase().toCharArray()[i] == 'o' | str.toLowerCase().toCharArray()[i] == 'u')
{
vowelCount++;
}
}
return vowelCount;
}
and if you want to include 'y', just add another comparison to the if statement
public static String countVowels(String count) {
int Vowelcount = 0;
String[] arr = count.split(" ");
//looping through string array
for (int i = 0; i <= arr.length - 1; i++) {
//looping through each character in the next element
for (char ch : arr[i].toCharArray()) {
//checking if ch == to vowels
if (ch == 'e' || ch == 'a' || ch == 'o' || ch == 'u' || ch == 'i') {
//add counts number of vowels for every string array index
Vowelcount += 1;
}
}
}
return Integer.toString(Vowelcount);
}
This should work just fine... I've split your words in the input string into a string array.

Removing vowels from an input string using a loop

I need my output to only be 5 characters long NOT counting the removed vowels. Currently my code is counting the input length and returning that number minus the vowels. This might be confusing. If I input "idontthinkso" it only returns "dnt" instead of what I want it to print out which is "dntth". Btw, I'm not allowed to use Stringbuilder or anything like that, only a loop, so forgive the code. How can I fix this? Here is my code:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for (int i = 0; i < tweetLengthAllowed; i++) {
char c = input.charAt(i);
if (c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u' ||
c == 'A' ||
c == 'E' ||
c == 'I' ||
c == 'O' ||
c == 'U') {
f = 1;
} else {
s = s += c;
f = 0;
}
}
System.out.println(s);
}
}
I'm very much in favor of using a while loop for this, but since you stated you can only use a for loop...
The problem is that your loop will iterate until i = 5, even if a vowel is detected. We need a way to tell the loop to pretend that never happened. You can't decrement i, or you'll be stuck at the same character forever.
Here's what I came up with, I decided to simply increment the tweetLengthAllowed to negate the i increment.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int f = 0;
int tweetLengthAllowed = 5;
for(int i = 0; i < tweetLengthAllowed; ++i) { //Must be a for loop
char c = input.charAt(i);
if(c == 'a'|| c == 'e'|| c == 'i'|| c == 'o'|| c =='u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
f = 1;
tweetLengthAllowed++; //Allows the loop to continue for one more interation
} //end if
else{
s = s += c;
f = 0;
}//end else
} //end for
System.out.println(s);
} //end main
} //end class
Also, if you're going to use a big chain of ORs, please do yourself a favor and make it more readable as I did above.
You can do this simpler. Here I iterate every char in the input and break if it reaches the limit:
import java.util.Scanner;
public class TweetCompressor {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String s = "";
System.out.println("Type a tweet: ");
String input = keyboard.nextLine();
int tweetLengthAllowed = 5;
int i = 0;
boolean isNotVowel;
boolean limitReached;
for (char c : input.toCharArray()) {
isNotVowel = "AEIOUaeiou".indexOf(c) == -1;
limitReached = tweetLengthAllowed <= i;
if (limitReached) { // exit the loop
break;
} else if (isNotVowel) { // append the char
s += c;
i++;
}
}
System.out.println(s);
}
}
Run output:
Type a tweet:
idontthinkso
dntth
Here is my way of doing it:-
import java.util.Scanner;
import java.lang.StringBuffer;
public class Program {
private static String RemoveVowel(String text)
{
int len = text.length();
char[]vowels = {'a','e','i','o','u','A','E','I','O','U'};
StringBuffer sb = new StringBuffer(text);
for(int i = 0;i<len;i++)
{
for(char v : vowels)
{
if(v == text.charAt(i))
{
sb.setCharAt(i,'\0');
}
}
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter some text to remove vowels from it: ");
String val = scan.nextLine();
System.out.println(RemoveVowel(val));
}
}
I have used string buffer to make the string modifiable and a "for" loop iterates through the length of the string, and one iterates through the "vowels" array; an "if" statement checks if the current character is equal to one of the vowels and if true, it sets the current character to null, which removes the vowel.
public class RemoveVowels {
public static void main(String[] args) {
String inputString = "Java - Object Oriented Programming Language";
System.out.println(inputString.replaceAll("[aeiouAEIOU]", " "));
}
}
Output:
J v - bj ct r nt d Pr gr mm ng L ng g

Counting Vowels, Repetition method

public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
for(int i = 0; i<=str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch =='A')
{
countVowelA++;
countVowel++;
}
if(ch == 'e' || ch =='E')
{
countVowelE++;
countVowel++;
}
if(ch == 'i' || ch =='I')
{
countVowelI++;
countVowel++;
}
if(ch == 'o' || ch =='O')
{
countVowelO++;
countVowel++;
}
if(ch == 'u' || ch =='U')
{
countVowelU++;
countVowel++;
}
i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}
For me i am having trouble, let's say for example if i type lebron james is the best basketball player, u know it. It gives me an error and also it doesn't count all the vowels? Also, can u tell if my code is right
check line below
for(int i = 0; i<=str.length(); i ++)
change to
for(int i = 0; i<str.length(); i ++)
why?
Because in Java, index start from zero. When you have i <= str.length, it goes beyond scope index of string and gives you java.lang.StringIndexOutOfBoundsException
Another issue, You have incremented variable i twice. Second after if clauses is totally unnecessary because it gives you wrong answer even if you rectify the boundary issue.
Your loop variable i, as was mentioned in the comments, is incremented twice. Once in the for statement itself, and the other at the end of the loop.
This means that the counter goes: 0,2,4,6 instead of 0,1,2,3.
That will give you the wrong answer.
However, the reason for the error is not this, but the fact that you check the condition until i <= str.length(), instead of i < str.length(). The characters in a string with, say, 3 characters like "the" are 0,1,2. There is no character number 3. So when i is equal to str.length, you get an error.
Try this code
import java.util.Scanner;
public class CountVowels {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
char[] c = str.toCharArray();
for(int i = 0; i<c.length; i ++)
{
if(c[i] == 'a' || c[i] =='A')
{
countVowelA++;
countVowel++;
}
else if(c[i] == 'e' || c[i] =='E')
{
countVowelE++;
countVowel++;
}
else if(c[i] == 'i' || c[i] =='I')
{
countVowelI++;
countVowel++;
}
else if(c[i] == 'o' || c[i] =='O')
{
countVowelO++;
countVowel++;
}
else if(c[i] == 'u' || c[i] =='U')
{
countVowelU++;
countVowel++;
}
//i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}

How to check if a character in a string is a digit or letter

I have the user entering a single character into the program and it is stored as a string. I would like to know how I could check to see if the character that was entered is a letter or a digit. I have an if statement, so if its a letter its prints that it's a letter, and the same for a digit. The code I have so far doesn't work but I feel like I'm close. Any help you can offer is appreciated.
System.out.println("Please enter a single character: ");
String character = in.next();
System.out.println(character);
if (character.isLetter()){
System.out.println("The character entered is a letter.");
}
else (character.isDigit()){
Syste.out.println("The character entered is a digit.");
You could use:
if (Character.isLetter(character.charAt(0))){
....
You could use the existing methods from the Character class. Take a look at the docs:
http://download.java.net/jdk7/archive/b123/docs/api/java/lang/Character.html#isDigit(char)
So, you could do something like this...
String character = in.next();
char c = character.charAt(0);
...
if (Character.isDigit(c)) {
...
} else if (Character.isLetter(c)) {
...
}
...
If you ever want to know exactly how this is implemented, you could always look at the Java source code.
Ummm, you guys are forgetting the Character.isLetterOrDigit method:
boolean x;
String character = in.next();
char c = character.charAt(0);
if(Character.isLetterOrDigit(charAt(c)))
{
x = true;
}
This is a little tricky, the value you enter at keyboard, is a String value, so you have to pitch the first character with method line.chartAt(0) where, 0 is the index of the first character, and store this value in a char variable as in char c= line.charAt(0)
now with the use of method isDigit() and isLetter() from class Character you can differentiate between a Digit and Letter.
here is a code for your program:
import java.util.Scanner;
class Practice
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Input a letter");
String line = in.nextLine();
char c = line.charAt(0);
if( Character.isDigit(c))
System.out.println(c +" Is a digit");
else if (Character.isLetter(c))
System.out.println(c +" Is a Letter");
}
}
By using regular expressions:
boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}");
char charInt=character.charAt(0);
if(charInt>=48 && charInt<=57){
System.out.println("not character");
}
else
System.out.println("Character");
Look for ASCII table to see how the int value are hardcoded .
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
char temp = yourString.charAt(0);
if(Character.isDigit(temp))
{
..........
}else if (Character.isLetter(temp))
{
......
}else
{
....
}
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
You need to convert your string into character..
String character = in.next();
char myChar = character.charAt(0);
if (Character.isDigit(myChar)) {
// print true
}
Check Character for other methods..
You could do this by Regular Expression as follows
you could use this code
EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();
if (Number.matches(NumberPattern) && s.length() > 0)
{
//code for number
}
else
{
//code for incorrect number pattern
}
I have coded a sample program that checks if a string contains a number in it! I guess it will serve for this purpose as well.
public class test {
public static void main(String[] args) {
String c;
boolean b;
System.out.println("Enter the value");
Scanner s = new Scanner(System.in);
c = s.next();
b = containsNumber(c);
try {
if (b == true) {
throw new CharacterFormatException();
} else {
System.out.println("Valid String \t" + c);
}
} catch (CharacterFormatException ex) {
System.out.println("Exception Raised-Contains Number");
}
}
static boolean containsNumber(String c) {
char[] ch = new char[10];
ch = c.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ((ch[i] >= 48) && (ch[i] <= 57)) {
return true;
}
}
return false;
}
}
CharacterFormatException is a user defined Exception. Suggest me if any changes can be made.

Categories