This code reads a notepad file this notepad file has the number 10 on it it returns a gibberish letter for some reason instead of 10 I think it is the ascii code but i do not know Also this code is modified from my programming teachers code so I do not take credit for it
/**
*Goes in to the file and extracts a number.
* @param fileName
* @return an integer
*/
static int getNumberFromFile(String fileName){
int j = 599;
try {
File textFile = new File(fileName);
Scanner sc = new Scanner(textFile);
String input = sc.nextLine();
j = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return j;
}
throws this wierd exception Exception: java.lang.NumberFormatException: For input string: "10" and this code
/**
* writes data for the ai to adapt its strategy
*@param number is the number to write
* @param fileName is the fileName
*/
public static void writeToFile(String fileName,int number) {
BufferedWriter output = null;
try {
File aFile = new File(fileName);
FileWriter myWriter = new FileWriter(aFile);
output = new BufferedWriter(myWriter);
output.write(number);
output.newLine();
output.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
System.out.println("please Report this bug it doesnt understand");
System.exit(1);
}
}
dont worry about some of the exception catch things those were for me to see if the exceptions are caught it just prints a (nonsense) message. and some of the stuff where a talk about an ai dont worry just need this code working I can post why the ai needs it but i dont think it is relevant
This line doesn't do what you expect:
output.write(number);
It's calling write
on a BufferedWriter
, so you should consult the documentation... at which point you find you're calling this method.
public void write(int c) throws IOException
Writes a single character.
Overrides:
write
in classWriter
Parameters:
c
-int
specifying a character to be written
And following the write
link gives more details:
Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored. Subclasses that intend to support efficient single-character output should override this method.
So, you're writing the Unicode character U+000A - or would be if the value were really 10. I strongly suspect it's not though, as that would just be a line feed character.
If you're trying to write the decimal representation of the number though, you should turn it into a string first:
output.write(String.valueOf(number));
See more on this question at Stackoverflow