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) {}
        }

    }
}
5
  • Wow, Wow, Wow, did you bother searching this beforehand? Commented Aug 28, 2014 at 21:01
  • Definite duplicate of How to read integer values from text file Commented Aug 28, 2014 at 21:02
  • I did search it, but I didn't see that question. I must not have gone through enough search results or just missed it. Sorry about that. Commented Aug 28, 2014 at 21:06
  • @meanIOstack, you're flagging as a dup of a dup. Why not mark the actual dup? Commented Aug 28, 2014 at 21:17
  • lol, it adds to the spice. Commented Aug 28, 2014 at 21:20

3 Answers 3

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

2 Comments

You are spoon feeding the child. Give a man a fish and he'll eat for a day.
@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.
0

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

Comments

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

}

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.