简体   繁体   中英

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

Sample Input #1

make(4)

Sample Output #1

{"0","1","2","3"}    


public class StringArrayOfNumbers {

static int testcase1 = 10;

public static void main(String args[]){
    StringArrayOfNumbers testInstance = new StringArrayOfNumbers();
    String[] result = testInstance.make(testcase1);
    System.out.println(result);
}

public String[] make(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;
}   

}

when i am trying to run code it prints only 4 times n , how to initialise this n? also without using any string library functions?

Testcase Pass/Fail Parameters Actual Output Expected Output

1 Fail '5' {'n','n','n','n','n'}{'0','1','2','3','4'}

n1 is a String which has the value " n " in it.

whereas n is a variable whose value varies from 0 to num - 1 .

SO you might want to assign n instead of n1 .

int n=0;
String[] arr=new String[num];
for(int i = 0; i < num; i++){
     arr[i]= n;
      n = n + 1;
    }

If you look closely, n and i have the same value, you don't need n too.

String[] arr=new String[num];
for(int i = 0; i < num; i++){
    arr[i] = i;
}

i'm not sure of what you are asking for, but the result should be this :

   public String[] make(int num) {

    int n = 0;
    //String n1 = "n";
    String[] arr = new String[num];
    for (int i = 0; i < num; i++) {
        arr[i] = String.valueOf(n);
        n = n + 1;
    }
    return arr;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM