0

I am trying to make a scoring system for a game I'm writing, but I need to be able to read an integer variable from a text document. I can easily get a String variable, but it won't come in as an integer. How would I go about doing that? Here is the code I have for reading and writing the score, but the input won't come in as an integer, as you can see when the println outputs the value of score2 integer. Thanks! I'm using an eclipse IDE for Java by the way.

import java.io.*;

public class ClassName {

    public static void main(String[] args) {

    FileOutputStream output;
    FileInputStream input;
    in score = 10;
    int integer = 4;
        try {
            output = new FileOutputStream("score.txt");
            new PrintStream(output).println(score);
            output.close();
        } catch (IOException e) {}

        try {
            input = new FileInputStream ("score.txt");
            int score2 = (new DataInputStream(score).readLine());
            input.close();
            System.out.println(score2);
        } catch (IOException e) {}
        }

    }
}
public static void
  • 95
  • 1
  • 6
  • 13

3 Answers3

0

To convert string to int you can use Integer.parse method

talex
  • 17,973
  • 3
  • 29
  • 66
0

I would use a Scanner and try-with-resources,

try (Scanner sc = new Scanner(new File("score.txt"))) {
  int score2 = sc.nextInt();
  System.out.println(score2);
} catch (IOException e) {
  e.printStackTrace();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • You are spoon feeding the child. Give a man a fish and he'll eat for a day. – Max Aug 28 '14 at 21:04
  • @MeanlOstack I searched the web as well as the stack overflow questions and didn't find what I was looking for. Elliott's advice was very helpful. I am a beginner programmer and need a lot of code to get what the answer is most of the time. – public static void Aug 28 '14 at 21:11
0

What you want to do is called parsing.

You want to use the parseInt() method of the Integer java class (link to doc)

try{
    Integer.parseInt(new DataInputStream(score).readLine())
} catch (NumberFormatException e) {

}
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164