Button Button - 7 months ago 39
Java Question

How to fix this encryption loop to read each character instead of first repeatedly

This is the version I'm working right now, where the loop does end but it just doesn't loop through each letter, instead it only repeats the first occurrence of the first letter.

For example, if

the ugly
and password was
it would repeat
(the position of
) four times (the length of ugly). Where as what I want it to do is repeat the loop four times (the length of ugly) but give back each position, not just the first (instead of
, I'm getting
4 5 6 7

Am I using the wrong kind of loop to achieve this? I've tried a few different ways and at this point I am stuck. Also if the answer is really obvious please don't burn me at the stake, I've only been programming for three months and have really given it a go on my own.

import java.util.Scanner;

public static void main(String[] args) {
String letter, sourcetext;
Scanner sc;
int temp;
sc = new Scanner(System.in);

sourcetext = sc.nextLine();
letter = sc.nextLine();

for (int i= 0; i < letter.length(); i++) {
temp = sourcetext.indexOf(letter);



You always use the same index: indexOf(letter). I guest what you want is:

for (int i= 0; i < letter.length(); i++) { 
    temp = sourcetext.indexOf(letter.charAt(i));