English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am trying to create a method in java that will scan for the location of the first vowel in a string, below is my code:
int x = 0;
String vowel = "aiueo",st = "";
boolean found = false;
for (int i = 0; i <= s.length()-1 && (found = false); i++ )
{
if (vowel.indexOf(s.charAt(i)) != -1)
{
st = s.charAt(i);
found = true;
}
}
x = s.indexOf(st);
return x;
}

but it generates a compiler error:

C:\Documents and Settings\Aditya Aditama H\My Documents\CSC\test\WordProcessor.java:172: incompatible types
found : char
required: java.lang.String
st = s.charAt(i);

why is that?

2006-10-29 10:20:17 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

Yes you are trying to convert a char into a String type. There are some things to do to solve it. One of them are to do the following in that error line:

st = String.valueOf( s.charAt(i) );

2006-10-29 10:33:00 · answer #1 · answered by sonfarX 4 · 0 0

The first thing that I noticed is that you are setting found to false in the for loop itself. I am not sure if you meant to make found equal to false when starting the loop, or if you wanted to stop the loop if found is not equal to true.

I will assume you want the loop to stop when found == true. You will have to change the found = false in the for loop to found == false, like so.
for (int i = 0; i <= s.length()-1 && (found == false); i++ )

This will do what you want.

In regards to the error you are getting, the other answerers provide two different ways of getting rid of the error. Both are correct, and if you wanted to implement the answer concerning creating a character for the character that is returned in s.charAt(i), change the following lines
int x = 0;
String vowel = "aiueo",st = "";
boolean found = false;

to
int x = 0;
String vowel = "aiueo";
char st = 0;
boolean found = false;

Then the program should run as you want.

2006-10-30 10:01:39 · answer #2 · answered by Mark aka jack573 7 · 1 0

s.charAt(i) is returning a character and st is a string so they are incompatible types.

Change st to char instead of string.

2006-10-29 18:23:25 · answer #3 · answered by Manish 5 · 0 0

fedest.com, questions and answers