1

My Question is following: Given a number n as input, return a new string array of length n, containing the strings “0″, “1″, “2″ so on till n-1. If n=0, return an array of length 0.The expected output is- stringArray(4) = {"0","1","2","3"} and the actual output is stringArray(4) = {0,1,2,3}.How can I add numbers in the form of string.

public class ArrayOfNumbers {

    static int testcase1=4;

    public static void main(String[] args){
        ArrayOfNumbers testInstance=new ArrayOfNumbers();
        String[] result=testInstance.arrayOfNumbers(testcase1);
        System.out.print("{");
        for (int i=0;i<result.length;i++){
            if (i>0)
                System.out.print(",");
            System.out.print(result[i]);
        }
        System.out.println("}");
    }

    public String[] arrayOfNumbers(int num) {
        int n=0;
        String n1="n";
        String[] arr=new String[num];
        for(int i=0;i<num;i++){
            arr[i]=n1;
            n=n+1;
        }
        return arr;
    }
}
3
  • 2
    Are you asking how to include " marks when you print each number? Commented Apr 1, 2014 at 20:36
  • 2
    You can use String.valueOf() to parse a number to a string. Commented Apr 1, 2014 at 20:40
  • @newbie don't forget to mark the post as 'solved' Commented May 13, 2016 at 12:13

3 Answers 3

2

Change your arrayOfNumbers method,

public String[] arrayOfNumbers(int num) {
    String[] arr = new String[num];
    for (int i = 0; i < num; i++) {
        arr[i] = "\"" + String.valueOf(i) + "\"";
    }
    return arr;
}

Then, you could use

String[] result = testInstance.arrayOfNumbers(testcase1);
System.out.println(Arrays.toString(result));

Or (to match your output exactly) use your existing main.

Sign up to request clarification or add additional context in comments.

2 Comments

i don't think he want to sourround his number with " ", but adding String to the array.
@AnthonyRaymond Take another look at the expected output (compared to the actual output). Obviously, I might be wrong... I have been before, and I'm sure I will be wrong again (I just don't think I am here).
2
public String[] arrayOfNumbers(int num) {
    String[] arr=new String[num];
    for(int i=0;i<num;i++){
        arr[i]="\"" + i + "\"";
    }
    return arr;
}

2 Comments

Also, he can get rid of n, and just use 'i' in it's place.
Add the solver marker to your post then :) Click on the cross on the left of an answer
1
for (int i=0;i<result.length;i++){
    if (i>0)
        System.out.print(",");
    System.out.print("\"" + result[i] + "\"");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.