The following method returns the position of the first occurrence of a given cha
ID: 3627658 • Letter: T
Question
The following method returns the position of the first occurrence of a given character in a given string. The position starts from 0 for the first character in the string. The method should return -1 if the character does not appear in the string. For example, the call indexOf('t',"iteration") would return 1, and the call indexOf('s',"iteration") would return -1. (You are not allowed to use the String indexOf method.)public static int indexOf (char c, String str)
I have:
System.out.print("Enter a string");
String str = in.nextLine();
char letter;
int pos =0;
int posCount=0;
while (pos<str.length())
{
if (str.charAt(pos)==letter)
{
posCount++;
}
else if (str.charAt(pos)!=letter)
{
pos++;
}
else
{
posCount= -1;
}
}
System.out.println(posCount);
I am getting an error that says index of cannot be resolved to a variable..
Explanation / Answer
please rate - thanks
import java.util.*;
public class Main
{
public static void main(String[] args)
{System.out.print("Enter a string: ");
Scanner in=new Scanner(System.in);
String str = in.nextLine();
char letter;
System.out.print("Enter letter to search for: ");
letter=in.nextLine().charAt(0);
System.out.println(indexOf(letter,str));
}
public static int indexOf (char c, String str)
{int pos =0;
int posCount=-1;
while (pos<str.length())
{
if (str.charAt(pos)==c)
return pos;
else
pos++;
}
return -1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.