193k views
4 votes
Consider the following method.

public static int mystery(String string1, String string2)
{
String temp = string1;
int position = 0;
int result = 0;
while(temp.indexOf(string2) >= 0)
{
position = temp.indexOf(string2);
result++;
temp = temp.substring(position + 1);
}
return result;
}
The following code segment appears in another method in the same class.
System.out.println(mystery("Mississippi", "si"));
What, if anything, is printed as a result of executing the code segment?
A 0
B 1
C 2
D 3
E Nothing is printed.

User Vamsidhar
by
8.3k points

1 Answer

4 votes

Final answer:

The code segment will print the number 2 as a result of executing the code.

Step-by-step explanation:

The code segment mystery("Mississippi", "si") will print the number 2 as a result of executing the code. The mystery method counts how many times the second string occurs inside the first string by using a while loop and the indexOf method. In this case, the second string is "si" and it occurs twice in the string "Mississippi", so the output will be 2.

User Efemoney
by
7.7k points