如何计算每个数字的空间?

时间:2011-05-14 21:04:54

标签: java string

我正在尝试创建一个显示您的网络信息的程序,而我正试图让它看起来有点不错。到目前为止它是CLI,这里是我遇到问题的代码:

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("+-------------------------------------+");
        }

    }
}

我需要它,如果空间中有9个,它会有9个空格。 我该怎么做?谢谢! :d

3 个答案:

答案 0 :(得分:3)

您可以使用StringBuilder:

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

作为旁注(但很重要) - 请勿使用==来比较字符串,而应使用equals / equalsIgnoreCase()。 (router.equals("0.0.0.0")代替router == "0.0.0.0"

答案 1 :(得分:2)

您可以使用String#format()

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

您甚至可以通过printf()使用它。

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

作为完全不同的选择,请使用Arrays#fill()

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

答案 2 :(得分:0)

我不太清楚这个问题,但也许你正在寻找一个for循环?