I have a small homework application that writes random numbers from 5 to 77 to a text file, and then a separate application that reads the file and totals the numbers.
Here is my code for writing the numbers to the text file…
Random r = new Random();
int min = 5;
int max = 77;
int[]randomNumbers = new int[1000];
try
{
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("myTextFile.txt")), true);
for(int i = 0; i < randomNumbers.length; i++)
{
randomNumbers[i] = r.nextInt(max - min + 1) + min;
pw.println(randomNumbers[i]);
}
}
catch(IOException io){}
Here is my code for reading the file and totalling the amount…
int totalAmount = 0;
public void run()
{
try
{
BufferedReader buffy = new BufferedReader(new FileReader("myTextFile.txt"));
String s;
while((s = buffy.readLine()) != null)
{
int number = Integer.parseInt(s);
totalAmount += number;
System.out.println(totalNumbers);
}
}
catch(IOException io){}
}
The output however starts with 29633 and displays numbers all the way to 42328
Why do I get this result… just trying to understand the wrong part of my code
Do you need to print out each number from the file, or only print out the total?
If you need to print each number, the
whileloop in your total application should look like this…However, if you only need to print out the final result, you need to move the
System.out.println()line outside thewhileloop (and still change the variable to totalAmount …