Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String representation of all values of nums, with the values separated by spaces

Here is the code I thought should work but I am missing something:

public String arrayToString(int[] nums){
      String str;
      int[] results = new int[nums.length];
       for(int i = 0; i < nums.length; i++){
          String string = "[1 , 2, 3, 4]";
       }
      return str;
}

This should return all the values of nums with spaces or do I need to switch the string?

I have tried to use the toString option which for some reason is not allowed in the IDE I am using as it is not using JRE 17 I believe the error message said. So that was not an option since I could not use java.lang.String.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re actually doing quite nothing to reach your goal, you don’t use nums values, and have defined a strange String string = "[1 , 2, 3, 4]";


You need to append all the values of nums to reach your goal, here are some ways

An array-style with existing method

// '[1, 5, 8, 98]'
public static String arrayToString(int[] nums) {
    return Arrays.toString(nums);
}

A concatenatde-values style

// '1,5,8,98'
public static String arrayToString(int[] nums) {
    StringBuilder result = new StringBuilder();
    String separator = "";
    for (int num : nums) {
        result.append(separator).append(num);
        separator = ",";
    }
    return result.toString();
}

Same with brackets

// '[1,5,8,98]'
public static String arrayToString(int[] nums) {
    StringBuilder result = new StringBuilder("[");
    String separator = "";
    for (int num : nums) {
        result.append(separator).append(num);
        separator = ",";
    }
    return result.append("]").toString();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading