使用数组的内容来打印String

时间:2015-11-23 02:13:28

标签: java arrays

我编写了这段代码,它接受一个整数数组的内容,并根据数组中的数字是否大于,等于或小于50将其转换为4个字母的字符串。我很担心方法的长度和冗余虽然?

  public static String computePersonality(int[] percentB) {
     String personality = "";
     if (percentB[0] < 50) {
        personality += "E";
     } else if (percentB[0] > 50) {
        personality += "I";
     } else { 
        personality += "X";
     }   
     if (percentB[1] < 50) {
        personality += "S";
     } else if (percentB[1] > 50) {
        personality += "N";
     } else {
        personality += "X";
     }   
     if (percentB[2] < 50) {
        personality += "T";
     } else if (percentB[2] > 50) {
        personality += "F";
     } else {
        personality += "X";
     }
     if (percentB[3] < 50) {
        personality += "J";
     } else if (percentB[3] > 50) {
        personality += "P";
     } else {
        personality += "X";
     }
     System.out.println(personality);
     return personality;
  }                       

2 个答案:

答案 0 :(得分:2)

您可以将逻辑提取到一个方法中,该方法根据单个int的值返回两个字符之一。像,

private static char computeChar(int percent, char low, char high) {
    if (percent < 50) {
        return low;
    } else if (percent > 50) {
        return high;
    }
    return 'X';
}

然后您的computerPersonality可能会像

那样实现
public static String computePersonality(int[] percentB) {
    StringBuilder sb = new StringBuilder(4);
    sb.append(computeChar(percentB[0], 'E', 'I'));
    sb.append(computeChar(percentB[1], 'S', 'N'));
    sb.append(computeChar(percentB[2], 'T', 'F'));
    sb.append(computeChar(percentB[3], 'J', 'P'));
    System.out.println(sb);
    return sb.toString();
}

答案 1 :(得分:0)

public class Snippet {

public static void main(String[] args) {
    computePersonality(new int[] { 5, 5, 50, 200 });
}

public static String computePersonality(int[] percentB) {
    String personality = "";
    String[] array = { "X","E", "I", "S", "N", "T", "F", "J", "P" };

   // Works when array.length-1=percentB.length*2;
    for (int value : percentB)
        personality += array[value == 50 ? 0 : (personality.length() * 2 + 1 + (value < 50 ? 0 : 1))];

    return personality;
}
}
  

for:

的说明

if(value == 50)add&#34; X&#34;(array [0])否则在数组中添加字母 personality.length * 2

+ 1 (因为我在位置0的数组中添加了X,所以我从位置1开始)

+ 0 | 1 (基于算法的逻辑。

您可以在同一逻辑上添加数组中的更多字母,它会起作用。