Next Character Check in Java - java

String input = "a == b";
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if(c == '='){
System.out.println("Assignment Operator");
}
}
In the above example if character is '=' and the next character is also '=' then print Comparison Operatorotherwise print Assignment Operator

You can do something like this
for(int i = 0; i < input.length() - 1; i++){
if(input.charAt(i) == '=') {
if(input.charAt(i + 1) == '=') {
System.out.println("Comparison Operator");
}
else {
System.out.println("Assignment Operator");
}
break;
}
}

The solution is simple:
if(input.charAt(input.indexOf("=") + 1) == '='){
System.out.println("Comparison Operator");}else{
System.out.println("Assignment Operator");
}

You can either use the strings class substring method, or the charAt method or you could use the contains these all would allow you to do what you want.

Related

Attempting to remove characters from a string

I am attempting to remove vowels from a randomly generated 20 letter word. I have to use substring for this assignment but am having issues with it conceptually. With this code, the value of word never changes and stays its original value. When I do i+2 for the second half of the string it jumps two characters and messes up when there are two vowels directly after one another. If I have to use substring how can I improve this to work every time.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
for(int i = 0; i < 20; i++) {
if(word.charAt(i) == 'a') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'e') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'i') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'o') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'u') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'y') {word = word.substring(0, i) + word.substring(i++);}
System.out.println(word);
}
finalWord = word;
}
public String getWord()
{
return finalWord;
}
}
You can use the simplified code as below to do so:
public static void main(String[] args) {
String stringPara = "this example will remove the vowals aeiou";
stringPara = removeCharFromString(stringPara, "a");
stringPara = removeCharFromString(stringPara, "e");
stringPara = removeCharFromString(stringPara, "i");
stringPara = removeCharFromString(stringPara, "o");
stringPara = removeCharFromString(stringPara, "u");
System.out.println(stringPara);
}
public static String removeCharFromString(String str, String characterToRemove){
while(str.contains(characterToRemove)){
str = str.substring(0, str.indexOf(characterToRemove)) + str.substring(str.indexOf(characterToRemove)+1, str.length()) ;
}
return str;
}
Why won't you use a simple Regex?
String str = "Hello world!";
str = str.replaceAll("[AEIOUaeiou]", "");
The new value of str will be Hll wrld!
The problem is in your i++ operator. It messes up both your character checking as well as your loop. The post decrement operator (i++) takes the original value of i as method argument but increases its value by one for all subsequent instructions.
To illustrate this, let's assume the input is "Treyarch". Then, at index 2 the character at i is e. And the instruction
word = word.substring(0, i) + word.substring(i++); will have the following consequences:
word = Treyarch
i = 3
Not only does it not expel the vowel from the String it also messes up your index (i) . Because for the rest of the loop the i is 4 and when you enter the next iteration it will be 5, so your program never checks the first two if condition.
That being explained, the best practice for this solution would be to check for any of the conditions in one if statement and use immutable index. In other words:
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o' || word.charAt(i) == 'u' || word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i + 1);
}
You got a problem with your incrementation logic. When you remove a char, you missed the following one.
Your code could be easier to read if you use switch statements.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
// don't go too far !!
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
// remove this vowel
word = word.substring(0, i) + word.substring(i + 1);
// step back in order to analyse the new i-th char
i--;
}
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}
public static void main(String[] args)
{
String WordsWithoutVowels ="mayank";
String updated="";
for(char char1: WordsWithoutVowels.toCharArray())
{
switch(char1)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
updated+=char1;
}
}
System.out.println(updated);
}
I fixed your original solution. First of all - iterate over each letters - to word.length(). Other problem was with increasing "i".
for (int i = 0; i < word.length(); ) {
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'e') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'i') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'o') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'u') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
Here more elegant way:
public class WordsWithoutVowels {
String finalWord;
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
public WordsWithoutVowels(String word) {
for (int i = 0; i < word.length(); ) {
if (vowels.contains(word.charAt(i))) {
word = word.substring(0, i) + word.substring(i + 1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}
simplified your solution to meet the requirement.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
StringBuilder sb = new StringBuilder(word);
for(int i = 0; i < sb.length;) {
if(sb.charAt(i)=='a' || sb.charAt(i)=='e' || sb.charAt(i)=='i' || sb.charAt(i)=='o' || sb.charAt(i)=='u')
sb.deleteCharAt(i);
else
i++;
}
finalWord = sb.toString();
}
public String getWord()
{
return finalWord;
}
}
public WordsWithoutVowels(String word) {
for (int i = 0; i < 20; i++)
{
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'e') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'i') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'o') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'u') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } if (word.charAt(i) == 'y') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } System.out.println(word + " " + i);
} finalWord = word; }

how to check if the char in a string is the same as the previous char?

The problem asks to compare if the string has consecutive same letters and rewrite it as the number of the letter plus the letter, for example, AAAAA as in 5A. But when I use the if statement to make the comparison the output become some very long number instead of the desired result.
Here is a portion of the problem:
Run-length encoding is a simple compression scheme best used when a dataset consists primarily of numerous, long runs of repeated characters. For example, AAAAAAAAAA is a run of 10 A’s. We could encode this run using a notation like *A10, where the * is a special flag character that indicates a run, A is the symbol in the run, and 10 is the length of the run.
Here is the code:
import java.util.Scanner;
public class RunLengthEncoding {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter input string: ");
String s = input.nextLine();
for (int a = 0; a < s.length(); a++) {
if ((s.charAt(a) < 'A' || s.charAt(a) > 'Z')) {
System.out.print("Bad input");
System.exit(0);
}
}
System.out.print("Enter flag character: ");
char flag = input.nextLine().charAt(0);
if (flag == '#' || flag == '$' || flag == '*' || flag == '&') {
int count = 0;
for (int i = 1; i < s.length(); i++) {
if(s.charAt(i)=s.charAt(i-1));
count++;
if (count == 1)
System.out.print(s.charAt(i));
if (count == 2)
System.out.print(s.charAt(i) + s.charAt(i));
if (count == 3)
System.out.print(s.charAt(i) + s.charAt(i) + s.charAt(i));
else
System.out.print(flag + s.charAt(i) + (count + 1));
}
} else
System.out.print("Bad input");
}
}
Your problem is here:
if(s.charAt(i)=s.charAt(i-1));
First of all, you must compare chars using == not =. Second, putting a ; right after the if statement will cause it to terminate immediately. In other words, the following line is no longer part of the if statement. Change to:
if(s.charAt(i) == s.charAt(i-1))
Edit
Regarding your comment, something like this should work, though I didn't test it. Just replace your current large if block with the below:
if (flag == '#' || flag == '$' || flag == '*' || flag == '&') {
char last = ' ';
char curr = ' ';
int count = 1;
for (int i = 0; i < s.length(); i++) {
last = curr;
curr = s.charAt(i);
if (curr == last) {
count++;
} else if (last != ' ') {
System.out.print(("" + count) + last);
count = 1;
}
}
System.out.print(("" + count) + last);
}

in function findVowels for loop increment doesn't work, only prints the last vowel?

here in the findVowels function I am trying to print every 2nd vowel which I got from outPut function in rev but it just print the last vowel only....
import java.util.Scanner;
public class VowelString {
static char rev;
static String str;
static int count = 0;
void inPut() {
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
System.out.println(str);
sc.close();
}
void outPut() {
System.out.println(str);
// int length=str.length();
try {
for (int i = 0; i <= str.length() - 1; i++) {
if ((str.charAt(i) == 'a') || (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i') || (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u')) {
rev = str.charAt(i);
System.out.print(rev);
count++;
}
}
// System.out.println(rev);
System.out.println("\ntotal " + count);
} catch (IndexOutOfBoundsException e) {
System.out.println(e);
}
}
void findVowels(char word) {
this.rev = word;
String asta = String.valueOf(rev);
for (int i = 0; i <= asta.length() - 1; i = +2) {
char nawa = asta.charAt(i);
System.out.println("something = " + nawa);
}
}
public static void main(String[] args) {
VowelString vS = new VowelString();
vS.inPut();
// System.out.println("Values of Input " + vS);
vS.outPut();
// System.out.println("Values of OutPut " + vS);
vS.findVowels(rev);
}
}
You are only saving the last vowel you find to rev
rev = str.charAt(i);
inside output(). So rev in findVowel will only be 1 char it seems. Perhaps you mean to say
rev += str.charAt(i);
Though this is not recommendable in a general setting it will probably suffice for your problem unless you have huge Strings.
The posted code should print all vowels. Not only the last as you say. But also not every 2nd as you want. It's also poorly written. Here's one way to print every second vowel, and a bit better written overall:
for (int i = 0, count = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
if (count % 2 == 0) {
System.out.print(c);
}
break;
}
}

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);
}
}

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

Categories