0

I'm really confused about how to use the java for each - loop correct. Can anyone help me?

Okay, so here is the deal. I've got an extended Collatz problem that I can't get out of my head. The thing is that I want to list all Collatz iterations for the range between two variables x and y where x>y in range 0-10000. My problem is that in the second foor-loop I want to execute the whole collatz-calculation on each number in value so if value = 7 I want to calculate the collatz-iterations for x = 7 (16) and so on up to y = 19 (20), the whole sequence being 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20. I'm doing this in Java.

import java.util.; import java.lang.;

public class hackCollatz{

public static void main(String[] args){

    Scanner input = new Scanner(System.in);

    int x;
    int y;
    int result = 0;

    System.err.print("Sätt ett värde på x: ");
    x  = input.nextInt();
    System.err.print("Sätt ett värde på y: ");
    y = input.nextInt();

    List<Integer> storeValue = new ArrayList<Integer>();

    for(int i=x; i<=y; i++){
        int value = i;
        storeValue.add(value);
        }       

    for(Integer value : storeValue){
        for(int j = value; j > 1; j++){
            if(j % 2 == 0){
                j=j/2;
            //  System.out.println(j);
                result++;

            }
            else{
                j=j*3+1;
                result++;
        //      System.out.println(j);
            }
        }
        }
        System.out.println(result);
        }       

}

  • `for(int j = value; j > 1; j++)`.. won't this result in an infinite loop? Unless I am missing something, because `j` is incremented with each iteration, it will always be greater than 1. You should use `j--` instead. – mfjones Feb 07 '13 at 23:08
  • Ah, I will try that. I'm tired. ;) But It still doesn't work as intended. I'm really confused... – Bobby Falck Feb 07 '13 at 23:11
  • Oh, I see the problem. You don't want to modify `j` during the iteration at all. So just use `for(int j = value; j > 1;)` (since you modify `j` inside the loop anyway). – mfjones Feb 07 '13 at 23:20

1 Answers1

0

If you change your inner FOR loop to: for(int j = value; j > 1;), then if value = 7, it will take 16 iterations to reach the value 1 (as expected).

mfjones
  • 739
  • 4
  • 16