1

This is the content of my Input file:

123

I want to take this input content to a int[] Array My code:

BufferedReader br = new BufferedReader(new FileReader("yes.txt"));
int[] Array = br.readline().toCharArray(); // Error as it has to be int array

How to solve this: output:

Array[0]=1
Array[0]=2
Array[0]=3
  • check http://stackoverflow.com/questions/7413830/java-read-line-from-file look at @T.J. Crowder answser – adhg Sep 20 '14 at 12:42

3 Answers3

1

Simple convert of your string to int array:

private int[] convertStringToIntArray(String str) {
    int[] resultArray = new int[str.length()];
    for (int i = 0; i < str.length(); i++)
        resultArray[i] = Character.getNumericValue(str.charAt(i));

    return resultArray;
}
Mykola Evpak
  • 156
  • 6
0

Once you have your string in, it's very simple.

I would recommend using an arraylist for this, as it is easier to add new elements on the fly.

String inputNumbers = "12345";
ArrayList<Integer> numberList = new ArrayList<Integer>();
for(int i = 0; i < inputNumbers.length(); i++) {
    numberList.add(Integer.valueOf(numberList.substring(i,i+1)));
}

And there you go! You now have an arraylist called numberList where you can access all of the numbers with numberList.get(0), numberList.get(1), etc.

Alex K
  • 8,269
  • 9
  • 39
  • 57
0

First read the input as string then convert to int array as below

  String inputString = br.readline()
  int[] num = new int[inputString.length()];

    for (int i = 0; i < inputString.length(); i++){
        num[i] = inputString.charAt(i) - '0';
    }

Another way is to convert the char array to int array

 char[] list = inputString.toCharArray();
int[] num = new int[inputString.length()];

for (int i = 0; i > inputString.length(); i++){
    num[i] = list[i];
}
System.out.println(Arrays.toString(num));
M Sach
  • 33,416
  • 76
  • 221
  • 314