Home > Software design >  How can I amend my code related to loops to produce the expected output using java?
How can I amend my code related to loops to produce the expected output using java?

Time:04-24

So I want to print out something like this when the 'r' argument is integer 5 (Expected output):

0 5
1 4
2 3
3 2
4 1
5 0

And this is my code currently:

public class RandomWalker {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        for (int i = 0; i <= r; i  ) {
            for (int j = r; j >= 0; j--) {
                System.out.println(i   " "   j);
            }
        }
    }
}

Instead I got this output:

0 5
1 5
2 5
3 5
4 5
5 5

I know that I can't add "break;" after the "System.out.println(i " " j);" line. What should I amend in my current code to produce the expected output? Thank you!

CodePudding user response:

You don't need two for-loops. Try this:

public class RandomWalker {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        for (int i = 0; i <= r; i  ) {
                System.out.println(i   " "   5-i);
        }
    }
}

If you want to use two variables, then you can do something like this instead:

public class RandomWalker {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        int j = r;
        for (int i = 0; i <= r; i  ) {
                System.out.println(i   " "   j);
                j--;
        }
    }
}

CodePudding user response:

Try a stream:

IntStream.rangeClosed(r)
   .mapToObj(n -> n   " "   (r - n))
   .forEach(System.out::println);

CodePudding user response:

My java is rusted, but something like this should work :

public class RandomWalker {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        String string ="";

        for (int i = 0; i <= r; i  ) {
            string = i   " "   (r - i);
            System.out.println(string);
        }
    }
}

CodePudding user response:

You'll have to merge the 2 loops into one:

public class RandomWalker {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        for (int i = 0, j = r; i <= r; i  , j--) {
            System.out.println(i   " "   j);
        }
    }
}
  • Related