0

Hello i would like to know the best and easiest way to scan an int number from a txt file one digit after another the numbers i can find is 0 to 9 non else for example:

24351235312531135

i want to get each time im scanning these inputs

2 
4
3
5
1
2

EDIT:

My input in txt file is something like this
 13241235135135135
 15635613513513531
 13513513513513513
 13251351351351353
 13245135135135315
 13513513513513531

6 lines with a known number of digits .... i have found this code but is not working

import java.util.Scanner;


public class ScannerReadFile {

public static void main(String[] args) {

    // Location of file to read
    File file = new File("data.txt");

    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

}

im unable to find the exact query im facing

  • 2
    Which one is your input? a One-line number of lines of numbers? – luiges90 Feb 15 '13 at 13:11
  • `im unable to find the exact query im facing` this is disappointing. What do you mean by your code is not working ? What output/error your are getting ? – Apurv Feb 15 '13 at 13:13

4 Answers4

2

Try this:

public static void main(String[] args) {
    File file = new File("data.txt");
    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            for (int i = 0; i < line.length(); i++) {
                System.out.println(line.charAt(i));
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
1

you need a for loop :

for(int i=0;i<line.length();i++)
System.out.println(Integer.parseInt(line.charAt(i)));
Arpit
  • 12,767
  • 3
  • 27
  • 40
0

Check this example on how to open and read a file in Java: http://alvinalexander.com/blog/post/java/how-open-read-file-java-string-array-list

Check also this SO question: Java File - Open A File And Write To It

Community
  • 1
  • 1
Blaise
  • 7,230
  • 6
  • 43
  • 53
0

You could iterate over the characters for each line:

while (scanner.hasNextLine()) {
   String line = scanner.nextLine();
      for (char c: line.toCharArray()) {
        System.out.println(c);
      }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276