t.h.h
t.h.h

Reputation: 31

Use contents of an array to print a String

I have written this code that takes the content of an integer array and converts it into a string of 4 letters based on if the number in the array is greater than, equal to, or less than 50. I'm worried about the length of the method and the redundancy though?

  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;
  }                       

Upvotes: 3

Views: 61

Answers (2)

GOXR3PLUS
GOXR3PLUS

Reputation: 7255

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;
}
}

Explanation of for:

if(value==50) add "X"(array[0]) else add the letter from array in the position personality.length*2

+1(because i added X in the array at position 0 so i start from position 1)

+0|1(based on the logic of your algorithm.

You can add more letters in array on the same logic and it will work.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

You could extract your logic into a method that returns one of two chars based on the value of a single int. Something like,

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

Then your computerPersonality might be implemented with something like

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

Upvotes: 2

Related Questions