电量显示

自从有了智能手机,时刻都要关心手机的电量。你的任务很简单,用程序打印符号来表示当前手机的电量。

用10行和10列来表示电池的电量,同时在外围加上边框,每一行表示10%的电量。 假设还有60%的电量,则显示如下:

+----------+
|----------|
|----------|
|----------|
|----------|
|++++++++++|
|++++++++++|
|++++++++++|
|++++++++++|
|++++++++++|
|++++++++++|
+----------+

多组测试数据,第一行为测试数据组数N(N<10),紧接着是N行,每行一个数,表示电量,这个数值可能是0,10,20,30,40,50,60,70,80,90,100 每组数据输出一个电池的电量,每组数据之间用15个“=”隔开 例如: 50%和0%

+----------+
|----------|
|----------|
|----------|
|----------|
|----------|
|++++++++++|
|++++++++++|
|++++++++++|
|++++++++++|
|++++++++++|
+----------+
===============
+----------+
|----------|
|----------|
|----------|
|----------|
|----------|
|----------|
|----------|
|----------|
|----------|
|----------|
+----------+
===============

参考解答

static String[] template =new String[] {
    "+----------+",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "|----------|",
    "+----------+"};

public static void printCharge(int precent) {
  /*
   * 共12x12个字符 
   * 比如10%时 需要将第10行的-替换为+号 
   * 比如20%时 需要将第9~10行的-替换为+号 
   * 比如30%时 需要将第8~10行的-替换为+号 ...
   */
  int begin = 11 - precent / 10;
  int end = 10;
  StringBuilder sb = new StringBuilder(template.length);
  for (int i = 0; i < template.length; i++) {
    if (i >= begin && i <= end) {
      sb.append(template[i].replaceAll("-", "+"));
    } else {
      sb.append(template[i]);
    }
    sb.append("\n");
  }
  System.out.println(sb.toString().replaceAll("\\n$", ""));
}

public static void main(String[] args) {
  int[] array = { 30, 50, 0 };
  for (int i = 0; i < array.length; i++) {
    printCharge(array[i]);
    System.out.println("===============");
  }
}

results matching ""

    No results matching ""