简体   繁体   中英

java - looping through values

I am trying to create a nested for loops that will generate all the pairs in a range specified by the user, ranging from negative values to positive values. It is a little tough to explain, but here is the code I have:

public class test method {

    public static void main (String[] args) {

    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    int c = 3;
    int d = 4;

    for (int i = -a; i <= a; i++)
        for (int j = -b; j <= b; j++) {

            System.out.println(a+" and "+b+" vs "+c+" and "+d+"\n");

        }

    }

}

Given command line arguments 1 and 2, my desired output would be something like:

-1 and -2 vs 3 and 4

-1 and -1 vs 3 and 4

-1 and 0 vs 3 and 4

-1 and 1 vs 3 and 4

-1 and 2 vs 3 and 4

0 and -2 vs 3 and 4

0 and -1 vs 3 and 4

0 and 0 vs 3 and 4

0 and 1 vs 3 and 4

0 and 2 vs 3 and 4

1 and -2 vs 3 and 4

1 and -1 vs 3 and 4

1 and 0 vs 3 and 4

1 and 1 vs 3 and 4

1 and 2 vs 3 and 4

I assume the lack of brackets in the first for is a problem in the copy & paste, but if that's your real code you've got a problem there.

a = Math.abs(a);
b = Math.abs(b);

for (int i = -a; i <= a; i++) {
    for (int j = -b; j <= b; j++) {
        System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");
    }
}

Two things. First of all you should be printing i and j and second you should also consider negative values. Your for 's will fail since -a if a = -1 will result in

for (int i = 1; i <= -1; i++)

The condition will not be met and the iteration won't take place. By doing Math.abs you get the absolute value of the inputs and you can do the iteration from that negative value to the positive one. If both a and b are positive the abs method will return the same values (assigning a and b with the same values they already have).

Whatever should be done with c and d remains to be seen. Your desired output says you leave them as they are so I won't touch them by now.

looks reasonable, exception for the '-a' business (and printing the wrong variables)

Assuming a/b are always positive, try

for (int i = (0-a); i <= a; i++)
    for (int j = (0-b); j <= b; j++) {
        System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM