Lil' Dunno
Lil' Dunno

Reputation: 37

How do I rewind a for loop?

How do you rewind or go back to the start of a for loop?

I tried to use "x=0" in an else statement like this:

            outerloop:
            for(int x=0; x<arr.length; x++){
                if(counter == countnum){
                    if(arr[x]!=0){
                        temp1 = Integer.toString(arr[x]);
                        death = death + " " + temp1;
                        arr[x] = 0;
                        counter=1;
                    }
                }

                else{
                    counter++;
                }

                if(x==(arr.length-1)){
                    for(int y=0; y<arr.length; y++){
                        if(arr[y]!=0){
                            x=0;
                        }
                        else
                            break outerloop;
                    }
                }
            }

It doesn't work. I found out about the iterator, but I don't think it'd work, rather, I don't understand how it works.

Here's an update since nobody seems to understand my situation:

This is what I wanted to happen:

For the input: 1 2 3 4

an input sequence is 2, then output should be rearranged: 2 4 3 1 accordingly to the input sequence. So I tried to return the for loop count back to 0, but it only shows: 2 4. it doesn't return to x=0 where arr[x(which is =0)]. That's my problem.

If you want, here's my entire source code:

import java.util.Random;

import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.Dimension;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;

public class Josephus extends JFrame {

    JLabel title;
    JLabel men;
    JLabel count;
    JTextField mentext;
    JTextField countext;
    JTextArea display;
    JButton execute;
    JButton close;
    String menstring;
    String countstring;
    int menum;
    int countnum;
    Random rand = new Random();
    String generation = "Generated Men: ";
    String death = "Death Series:  ";
    int counter = 1;

    public Josephus(){

        super("");

        setLayout(null);

        title = new JLabel("Death Execution");
        title.setFont(new Font("Calibre", Font.BOLD, 20));
        title.setBounds(350, 15, 400, 25);
        add(title);

        men = new JLabel("Number of Men");
        men.setBounds(10, 60, 400, 25);
        add(men);

        mentext = new JTextField();
        mentext.setBounds(120, 60, 150, 25);
        add(mentext);

        count = new JLabel("Count of Death");
        count.setBounds(10, 100, 400, 25);
        add(count);

        countext = new JTextField(10);
        countext.setBounds(120, 100, 150, 25);
        add(countext);

        display = new JTextArea(5, 20);
        display.setEditable(false);
        display.setBounds(290, 60, 280, 200);
        add(display);

        execute = new JButton("Execute");
        execute.setBounds(105, 230, 80, 30);
        add(execute);

        execute.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                String temp;
                String temp1;
                menstring = mentext.getText();
                countstring = countext.getText();
                menum = Integer.parseInt(menstring);
                countnum = Integer.parseInt(countstring);

                int arr[] = new int[menum];

                for(int x=0; x<arr.length; x++){
                    if(x!=0){
                        if(arr[x]!=arr[x-1])
                            arr[x] = rand.nextInt(500)+1;
                        else
                            x--;
                    }
                    else
                        arr[x] = rand.nextInt(500)+1;
                }

                for(int x=0; x<arr.length; x++){
                    temp = Integer.toString(arr[x]);
                    generation = generation + " " + temp;
                }

                outerloop:
                for(int x=0; x<arr.length; x++){
                    if(counter == countnum){
                        if(arr[x]!=0){
                            temp1 = Integer.toString(arr[x]);
                            death = death + " " + temp1;
                            arr[x] = 0;
                            counter=1;
                        }
                    }

                    else{
                        counter++;
                    }

                    if(x==(arr.length-1)){
                        for(int y=0; y<arr.length; y++){
                            if(arr[y]!=0){
                                x=0;
                            }
                            else
                                break outerloop;
                        }
                    }
                }

                display.setText(generation + "\n" + death);
            }
        });

        close = new JButton("Close");
        close.setBounds(200, 230, 70, 30);
        add(close);

        close.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                System.exit(0);
            }
        });
    }

    public static void main(String[] args){
        Josephus frame = new Josephus();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setSize(600, 330);
        frame.setVisible(true);

    }

Here's something...

This is a JOSEPHUS EXECUTION program...

Edit:

I found a solution.

Upvotes: 0

Views: 719

Answers (5)

philipxy
philipxy

Reputation: 15118

The for loop

for(int x=0; x<arr.length; x++)

initializes x=0 at the beginning. (Its first expression.) Before each execution of the body of the loop it tests x<arr.length. (Its second expression.) After the body of the loop but before the next test it executes x++. (The third expression.)

So the x++ of the for(int x=0; x<arr.length; x++) happens after all the code in the loop. Then the test is re-done. You want x to be 0 when you get back to the test at the top of the loop. But in the if when arr[y]!=0 you are setting x to 0 and then the x++ in the for loop makes it 1 before the test is redone.

So you need to set x=-1. Then the x++ in the for loop makes it 0 before the test is redone. Then the test is re-done with x 0.

PS (After googling what you are not explaining.) (Although your code seems want to execute down to no survivors so I'll assume that.)

The top if "executes" the xth element of arr by setting it to zero if it is the countnumth nonzero arr element after the last one modulo arr.length. If the bottom if wrapped x back to -1 from arr.length-1 (per above) then a third statement could break the main loop when arr is all zero. Or if the bottom if wrapped x back to the first non-zero element of arr via x=y-1 inside the for(int y=0; y<arr.length; y++) then afterwards you could break from the main loop when x==arr.length-1. But unfortunately your current code exits the main loop from the loop that looks for the next non-zero element as soon as a zero element is found.

Upvotes: 4

Blue
Blue

Reputation: 557

Instead of rewinding a for loop, just set the values yourself.

int[] copy = arr;
copy[0]=arr[1];
copy[1]=arr[3];
copy[3]=arr[1];
arr=copy;

Sure it's a hack job, but because the purpose of a loop is to simplify things (which is not happening in your case), the easiest thing to do is not use a loop.

Upvotes: 0

WalterM
WalterM

Reputation: 2706

It's best not to get hacky when restarting loops.

int totalTimesRun = 0;

MAIN_LOOP:
while(true){
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            System.out.println(i + ", " + j);
            if(j == i && i == 1 && ++totalTimesRun < 3) {
                System.out.println("Restarting Loop");
                continue MAIN_LOOP;
            }
        }
    }


    break; //will always break out of MAIN_LOOP
           //unless continue MAIN_LOOP is called
}

Output

0, 0
0, 1
0, 2
1, 0
1, 1
Restarting Loop
0, 0
0, 1
0, 2
1, 0
1, 1
Restarting Loop
0, 0
0, 1
0, 2
1, 0
1, 1
1, 2  //since totalTimesRun is now 3 it runs
2, 0
2, 1
2, 2

The trick here is

while(true){
    //will only run once since break is at the end
    break;
}

Upvotes: 1

Eran
Eran

Reputation: 393811

Rewinding the loop by changing the value of the counter (x in your case) should work.

I suspect the problem in is your inner loop :

            if(x==(arr.length-1)){
                for(int y=0; y<arr.length; y++){
                    if(arr[y]!=0){
                        x=0;
                    }
                    else
                        break outerloop;
                }
            }

You only rewind x if arr[0]!=0. Otherwise you break from the loop. Even if you do rewind x, you may still break from the loop if arr[y]==0 for some y.

You can replace that code with :

        if(x==(arr.length-1)){
            for(int y=0; y<arr.length; y++){
                if(arr[y]!=0){
                    x=-1;
                    break;
                }
            }
        }

You don't need break outerloop, since the loop will end anyway if you don't reset x back to 0.

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

Here somthing wrong if arr[x] is an int ypou cant do this Integer.toString(arr[x]), if no you can't do this arr[x]!=0:

   if(arr[x]!=0){
    temp1 = Integer.toString(arr[x]);

Or maybe you mean:

     if(arr[x]!=0){
      temp1 = x;

Upvotes: 0

Related Questions