I'm a beginner in Java and I have a question regarding loops. I've been struggling with this task where it says: Write programs that read a line of input as a string and print the positions of all vowels in the string.
I have managed to print out the number of vowels in the input but I got stuck when it came to print out their positions.
Any help would be appreciated!
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
}
}
System.out.println(sum);
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
System.out.println("position ->"+i);//added line
}
}
System.out.println(sum);
you just needed to add single line that prints the positions
Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the >144,000 characters defined in Unicode.
Code point
To work with individual characters, use code point integer numbers.
Define your set of targeted vowels. Sort the array, so that we may search quickly via binary search.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray() ;
Get the code points of the characters in your input.
int[] codePoints = "test".codePoints().toArray() ;
Loop the array of code points of our input string, by index (zero-based counting). Test each code point to see if it is found within our array of vowel code points.
To go in the reverse direction, from code point integer to the character as text, call Character.toString.
Example code
Pull all the code together.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray();
int[] codePoints = "testy".codePoints().toArray();
List < Integer > indicesOfVowels = new ArrayList <>( codePoints.length );
for ( int index = 0 ; index < codePoints.length ; index++ )
{
int position = Arrays.binarySearch( vowelCodePoints , codePoints[ index ] );
if ( position >= 0 )
{
String vowel = Character.toString( codePoints[ index ] );
System.out.println( "Vowel: " + vowel + " | Index: " + index );
}
}
See this code run at Ideone.com.
Vowel: e | Index: 1
Vowel: y | Index: 4
Related
I'm a beginner in Java and I have a question regarding loops. I've been struggling with this task where it says: Write programs that read a line of input as a string and print the positions of all vowels in the string.
I have managed to print out the number of vowels in the input but I got stuck when it came to print out their positions.
Any help would be appreciated!
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
}
}
System.out.println(sum);
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
System.out.println("position ->"+i);//added line
}
}
System.out.println(sum);
you just needed to add single line that prints the positions
Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the >144,000 characters defined in Unicode.
Code point
To work with individual characters, use code point integer numbers.
Define your set of targeted vowels. Sort the array, so that we may search quickly via binary search.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray() ;
Get the code points of the characters in your input.
int[] codePoints = "test".codePoints().toArray() ;
Loop the array of code points of our input string, by index (zero-based counting). Test each code point to see if it is found within our array of vowel code points.
To go in the reverse direction, from code point integer to the character as text, call Character.toString.
Example code
Pull all the code together.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray();
int[] codePoints = "testy".codePoints().toArray();
List < Integer > indicesOfVowels = new ArrayList <>( codePoints.length );
for ( int index = 0 ; index < codePoints.length ; index++ )
{
int position = Arrays.binarySearch( vowelCodePoints , codePoints[ index ] );
if ( position >= 0 )
{
String vowel = Character.toString( codePoints[ index ] );
System.out.println( "Vowel: " + vowel + " | Index: " + index );
}
}
See this code run at Ideone.com.
Vowel: e | Index: 1
Vowel: y | Index: 4
I got 3 strings from the user as input.Then count the vowels in each word and print as follows.If the vowel count = 0 and 1 then print 0.If the vowel count = 2 then print 2.If the vowel count is greater than or equal to 3 then print 3.
I tried this code.
Scanner in = new Scanner(System.in);
String[] str = new String[3];
for (int i = 0; i<3; i++)
str[i] = in .nextLine();
for (int j = 0; j<3; j++) {
String s1 = str[j];
String s = s1.toLowerCase();
int count = 0;
for (int i = 0; i<s.length(); i++)
{
if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') {
count++;
}
if (s.charAt(i) == ' ') {
if (count == 0||count == 1) {
System.out.print("0");
} else if (count == 2) {
System.out.print("1");
} else {
System.out.print("3");
}
count = 0;
}
}
if (count == 0||count == 1) {
System.out.println("0");
} else if (count == 2) {
System.out.println("1");
} else {
System.out.println("3");
}
}
But there is one condition only print the vowel count for 3 words only even if the user enter the string with more than 3 words.For eg if the user gives the string "hi hello all, how are you,I am fine and u" it prints "010
011
001" like this only but this code prints as "010
011
00100".Now how can i change the code to print the vowel count only for 3 words and not for more than 3?
You need some kind of a break after the third word. One option would be to make an extra variable for tracking it and increment it when the character is space. After 3 words you could break the loop.
Other option would be to split the String into words with split() method and the iterate over the first 3 only.
You could simplify your code a lot and it will be easier to achieve what you want. Instead of loop on each char, you can split your string. And then loop on the words. Something like this:
for (int j = 0; j<3; j++) {
String[] words = str[j].toLowerCase().split(" ");
// Use Math.min, thanks that it works even if you have only 2 words
for(int i = 0; i < Math.min(3, words.length()); i++) {
int count = 0;
for (char letter : words[i].toCharArray()) {
// if letter is vowel: count += 1;
}
// System.out.println depending on count value
}
}
You could use a Regex to split words into a sentence, using this method:
String[] splits = myPhrase.split(" ");
to split words in a sentence, but you have to be careful that if the user enters more spaces, the first one is "eliminated" and those just after end up in the split.
For example:
String phrase = "1 2 3 z";
String[] splits = phrase.split(" ");
generates this array: [1|2| |3| | |z].
So, in my opinion, at that point you could use a filter, go through the array / list again eliminating any space derived from the regex or more simply when you scroll through the array / list and find a space you don't consider it.
At this point go to analyze the first 3 elements of the array / list, discarding the others (maybe using a counter).
Finally, again using a Regex, you can also check if the character you are analyzing is a vowel or not using this command:
if (s.charAt(i).matches("[AEIOUaeiou]")){ /*it's a vowel*/}
Can you guys, please, explain to me what does count[word.charAt(i)]++, exactly do in this code and overall--?
public static void main(String[] args) {
String S = "Some random text to test.";
int count[] = new int[124];
for (int i=0; i< S.length(); i++) {
count[S.charAt(i)]++;
System.out.print(count[S.charAt(i)] + " ");
}
int max = 1;
char result = ' ';
for (int i = 0; i < S.length(); i++) {
if (max < count[S.charAt(i)] && S.charAt(i) != ' ') {
max = count[S.charAt(i)];
result = S.charAt(i);
}
}
System.out.println(result);
}
The printing of count[S.charAt(i)] was just me trying to figure it out.
S.charAt(i) returns the character in the i-th position of that string S.
Then count[S.charAt(i)] will execute like this. Lets say you get 'S' as the character. Then the character value for 'S' will be 83. So, it will take the element of the 83 index in count array and increment it by one.
word.charAt(i) returns the character at the i-th index in the String word.
count is an int array with all zeros automatically : int count[] = new int[124];
count[i]++ increments the value that is in count at index i by 1.
Here, you're passing word.charAt(i) as an index i.e count[word.charAt(i)]++, and what it does is:
-Evaluate word.charAt(i) first, but
note that index i must be an integer!
so automatically gets the ASCII value of the character. For example ('a' = 97, 'b' = 98..)
-then, count[ASCII number returned]++, for example count[97]++, will be incremented and now count[97] = 1
But note that if your String has '}', there will be Index out of bound exception, since its ASCII value is 125; and 125 > 124 the size of count!
I was writing a code that counts special characters in a string prompt from the key board. This is the method.
public static int specislChar(String s){
int counter = 0;
char ch;
for (int i =0 ; i<=s.length(); i++){
ch = s.charAt(i);
if (!Character.isLetterOrDigit(ch) || ch != ' ') {
System.out.print(" " + ch);
counter++;
}
}
return counter;
}
Every time I call this method, at the System.out.print() it gives me an error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 20
your loop should be less than i<s.length(). it is the cause of StringIndexOutOfBoundsException and you have to use AND operator not OR
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (!Character.isLetterOrDigit(ch) && !Character.isSpaceChar(ch)) {
System.out.print(" " + ch);
counter++;
}
}
When debugging this kind of issues, always run you code step by step and check if what you wrote is doing what you expect at every step, it's a simple but invaluable technique :)
If you want to count chars that are not letter/digit/space, this:
|| ch != ' '
will always give true for every character that is not space, the check you need to to is this one:
if ( !(Character.isLetterOrDigit(ch) || (ch==' ')) ){
Or, applying De Morgan's Law:
if ( (!Character.isLetterOrDigit(ch)) && (ch!=' ') ){
The error you are getting is due to this line: for (int i =0 ; i<=s.length(); i++){. In Java, arrays are 0 based and run from 0 to n-1, where n is the amount of entries you have.
Thus, changing it to for (int i =0 ; i<s.length(); i++){ will remove the error.
Also, this: || ch != ' ' will be true for any non special character as well, which will cause inaccurate results. I think you mean && ch != ' '.
Example code:
public class ____QuickTester {
public static void main(String[] args) {
// This should be 11
System.out.println("Number of special characters: " +
specialChar("asdaskd12312!#(#(!##)(*asdas12301230"));
// This should be 8
System.out.println("Number of special characters: " +
specialChar("!a#b#c$d%e aaa bbb ccc !!!"));
}
public static int specialChar(String s) {
// Get rid of alphabets, digits and space
s = s.replaceAll("[A-Za-z0-9 ]", "");
return s.length();
}
}
Output:
Number of special characters: 11
Number of special characters: 8
A much simpler way would be to remove all alphabets, digits, and space
The remaining content will be the special characters
Change your for loop condition from <= to < to solve StringIndexOutOfBoundsException as array index start from 0 so it will go upto length-1.
i < s.length();
And use &&(And) operator instead of ||(Or) operator in if condition as you want to check both the conditions.
if (!Character.isLetterOrDigit(ch) && !Character.isSpaceChar(ch) )
Do something like this :-
public static int specislChar(String s) {
int counter = 0;
for (char ch : s.toCharArray())
if (!Character.isLetterOrDigit(ch) && ch != ' ')
counter++;
return counter;
}
Input :- %#%^&*(hi hello$!!+ #
Output :- 12
you are looping though i<=s.length(); but it should be i<=s.length()-1; because index starts at 0. If it starts at 0 then it should be only to length-1
// here i am try to find the location of a char in char array.
if character is resent in the array replace it's original value by its index that is an integer. but when i am try to compile it i got some non- printable out put.so please help me. i mean , when i try access the array element then effect of above operation must be seen.
class Re{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
char [] array = enter.toCharArray();
char find = input.next().charAt(0);
char find2 = Character.toUpperCase(find);
char find3 = Character.toLowerCase(find);
for (int i=0;i<array.length;i++)
{
if((find2==array[i])|| ( find3==array[i]))
{
array[i] = (char)(i);
}
else
{
array[i] =array[i];
}
}
for(i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
}
}
Unicode has a lot of non-printable characters. See ASCII table for the ones you are probably getting (first 127 characters of UTF-16 are same as ASCII). If you want to convert an integer to its corresponding character value what you can do is add '0' to it.
Ex:
if (find2 == array[i] || find3 == array[i]) {
array[i] = (char)(i + '0');
} // omit your else self-assignment, it is redundant
If i > 9 then it is not convertable to a numerical character (only single digit) so you would have to use Strings.
Ex:
String[] out = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] == findUp || array[i] == findLo) {
out[i] = String.valueOf(i);
} else {
out[i] = String.valueOf(array[i]);
}
}
You can also use Character#forDigit in the form of Character.forDigit(i, 10) which either returns the above expression ('0' + digit), an alphabetical character if the digit is > 9 ('a' + digit - 10) or a null character if the digit is outside the radix. IE Character.forDigit(10, 10) returns a null character but Character.forDigit(10, 16) (hex) returns 'a'.
When you cast between char and primitive number types (int, short, etc) what you are working with is the Unicode codepoint. For example (char)9 is actually the tab character. Unicode numbers correspond to codes 48-57. Because the numbers are contiguous (0 corresponds to 48, 1 corresponds to 49, 2 corresponds to 50, etc) you can add the value of '0' and get the corresponding character. For example 48 + 2 = 50 so '0' + 2 = '2'. Due to algebra you can also of course convert a character to an integer by subtraction IE '2' - '0' = 2.
You can make like this:
if ((find2 == array[i]) || (find3 == array[i])) {
array[i] = find;
}
else {
array[i] = array[i];
}