Home » Java » How can i only read Strings or Integers when i read .txt file with Scanner Class in Java

How can i only read Strings or Integers when i read .txt file with Scanner Class in Java

Posted by: admin July 12, 2018 Leave a comment

Questions:

Hey guys this is my first question so if i have any mistakes or faults , i am sorry about that.

So i am working on one thing which i’m currently keep failing of and that is ,as it says in the title, reading only strings and integers from .txt file. Here is my code:

 File file = new File("C:\\Users\\Enes\\Desktop\\test.txt");
    Scanner scn = new Scanner(file);
    String[] s = new String[10];
    int i = 0;
    int[] fruits = new int[10];

    while (scn.hasNextInt()) {

        fruits[i++] = scn.nextInt();

    }while (scn.hasNext()) {

        s[i++] = scn.next();

    }

    for (int elm : fruits) {
        System.out.print(elm + "\t");
        System.out.println("\n");
    }
    for (String ele : s) {
        System.out.print(ele + "\t");
    }

And here is what writes on .txt file

Apple 5
Pear 3

Output is like:

0   0   0   0   0   0   0   0   0   0   
Apple   5   Pear    3   null    null    null    null    null    null

So i want to get Apple and Pear, the strings in different array and 5 and 3 which is integers in different array. How can i do this? Any help would be so appreciated. Thanks all!

Answers: