开发者

How to do a space for every number counted?

开发者 https://www.devze.com 2023-03-06 11:29 出处:网络
I\'m trying 开发者_Python百科to make a program that displays your network information and I\'m trying to make it look just a little nice. It\'s CLI so far and here\'s the code I\'m having trouble with

I'm trying 开发者_Python百科to make a program that displays your network information and I'm trying to make it look just a little nice. It's CLI so far and here's the code I'm having trouble with:

public class Computer {
    String manu;
    boolean power;
    String powerStr;
    String internalIP;
    String router;
    boolean connected;
    int length;
    String extIP;
    String line;
    String netInfo;
    int netLength;
    int space;

    void setIntIP(String ip) {
        this.internalIP = ip;
        if(router == null) {
            System.out.println("There is no router to connect to!");
            this.internalIP = null;
        }
    }

    void printInfo() {
        if(power == true) {
            powerStr = "on";
        }
        else
        {
            powerStr = "off";
        }
        System.out.println("The computer is "+powerStr+" and was made by "+manu);
    }

    void routingInfo() {
        if(router == null) {
            internalIP = "0.0.0.0";
            router = "0.0.0.0";
        }
        if(internalIP == null) {
            internalIP = "0.0.0.0";
            router = "0.0.0.0";
        }

        if(router == "0.0.0.0") {
            System.out.println("Not connected to the internet!");
        } else {
            netInfo = "+-------Network Information-----------+";
            line = "| Internal IP | "+internalIP;
            length = line.length();
            netLength = netInfo.length();
            space = netLength - length;
            System.out.println("+-------------------------------------+");
        }

    }
}

I need it so that if there is 9 in space, it does 9 spaces. How would I do this? Thanks! :D


You can use StringBuilder:

StringBuilder sb = new StringBuilder();
// add info
for (int i=0; i < space; i++)
    sb.append(" ");
// add info
// print it using sb.toString()

As a side note (but an important one) - don't compare strings using ==, but with equals / equalsIgnoreCase(). (router.equals("0.0.0.0") instead of router == "0.0.0.0")


You can use String#format() for this.

int length = 9;
String spaces = String.format("%" + length + "s", " ");
System.out.println("|" + spaces + "|"); // | nine spaces |

You can even use it through printf().

int length = 9;
System.out.printf("%" + length + "s%n", " "); // Nine spaces and a linebreak.

As a completely different alternative, use Arrays#fill().

int length = 9;
char[] chars = new char[length];
Arrays.fill(chars, ' ');
System.out.println(chars);


I don't understand the question well , but maybe you are looking for a for loop ?

0

精彩评论

暂无评论...
验证码 换一张
取 消