简体   繁体   中英

How can I improve/reduce this piece of Java code

I had a task and I completed it: The objective was to create a method with 2 arguments: 1. the number to count, and 2. how many char/numbers is the total result.

Result: Let's say that "number" is 5, so it will count: 01234 5 43210 BUT it will also add spaces to the sides to complete the 2nd requirement "largo", so if long is 15, the result would be " 01234543210 " with 2 spaces to each side. So i wrote this piece of code, but other coder told me that he used half the lines I did.

There were many assumptions in the code, like the fact that largo is > than number or that if number is an odd number, largo is odd too.

So my question would be, can this code be reduced (refactored?) [I just have one month in my java path so be hard but understanding XD)

public static void counter(int number, int largo) {
    int numberFull=(number*2)+1;
    int spaceFull=largo-numberFull;
    int space=spaceFull/2;
    for (int a=1;a<=space;++a)
        {System.out.print(" ");}
    for (int x=0;x<=number;x++)
        {System.out.print(x);}
    for (int y=number-1;y>=0;y--)
        {System.out.print(y);}
    for (int b=1;b<=space;++b)
        {System.out.print(" ");}
}

Try this.

public static void counter(int number, int largo) {
    int space = (largo - (number * 2) - 1) / 2;
    String left = "0123456789".substring(0, number);
    String right = new StringBuilder(left).reverse().toString();
    String spaces = space > 0 ? String.format("%" + space + "s", "") : "";
    System.out.print(spaces + left + number + right + spaces);
}

number must be from 0 to 9.

I find your code fine (apart from the formating). For your (mathematical) entertainment;

int spaces = largo - (2*n + 1);
print("          ".substring(0, spaces/2));
long x = pow(111111111L % pow(10, n), 2);
if (x != 0) print(0);
print(x);
if (x != 0) print(0);
print("          ".substring(0, spaces - spaces/2));
// Or: printf("%" + (spaces - spaces/2) + "s", "");

I do not find this solution "nicer" - it has more restrictions. But it utilizes 111...111^2 == 123....321. It does away with for-loops.

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