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
1

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

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.