package stringAnalyze;
import java.util.Scanner;
public class CommonLetters {
public static void main(String[] args) {
getLetters("reba", "oeoe");
}
public static String getLetters(String firstInput, String secondInput) {
String newLetters=("");
for (int i=0; i <=firstInput.length(); i++){
for (int b=0; b <=secondInput.length(); b++) {
if (firstInput.charAt(i)==secondInput.charAt(b)) {
newLetters= (newLetters+ secondInput.charAt(b)+"");
}
}
}
return newLetters;
}
}

- 349,597
- 67
- 533
- 578

- 1
-
1You probably want `i < firstInput.length()` rather than `i <=firstInput.length()` – John Coleman Oct 09 '22 at 20:48
3 Answers
This is because you started from 0
to string_length
included.
The string is always from 0
to string_length-1
.
Solution:
simply remove =
sign from bool_expression on 2 for_loop => i < firstInput.length
.

- 321
- 1
- 11
Whenever you iterate from index 0, use <
(not <=
) to iterate upto complete length. You are iterating to 1 place beyond the index by using <=
.
Try this:
for (int i=0; i < firstInput.length(); i++){
for (int b=0; b < secondInput.length(); b++) {
if (firstInput.charAt(i)==secondInput.charAt(b)) {
newLetters= (newLetters+ secondInput.charAt(b)+"");
}
}
}

- 5,511
- 2
- 27
- 53
The length() function returns the actual length of a String, but when you are iterating through a String, the index is what you need to look at.
E.G. "Cat" is a String of length 3 (starts from 1). But when you are iterating through the same String, you need to watch out for the index. The index starts from 0. The index position of the String "Cat" will be C = 0, a = 1 and t = 2.
So there are two ways you could do this:
for (int i = 0; i < firstInput.length(); i++) {
// code
}
In the above for loop, you are iterating over the index. So assuming the String has the value Cat, you start at 0, and the index ends at 2.
for (int i = 0; i <= firstInput.length()-1; i++) {
// code
}
In this way, when you use <=, this means that you start at 0 and still end at 2, but you are decreasing the actual length of the String by 1.
Hope this helps.

- 452
- 5
- 24