Computer Science Canada Program wont run |
Author: | slider203 [ Wed Mar 10, 2010 11:48 pm ] |
Post subject: | Program wont run |
This program reads in numbers from a file then calculate the the numbers cube (e.g. 4x4x4) The for loop should run from 1-25, since there are 25 pairs of values in the file. Quote: import java.io.*; class FilesPrac2 { public static void main (String args[]) throws java.io.IOException { FileReader fr = new FileReader ("squares.txt"); BufferedReader bfr = new BufferedReader (fr); final int MAX = 25; int product = 0; int cube = 0; int loopNum = 0; int even_product = 0; String input = ""; // This loop will output the even integers the squares // and calculate and output the cubes of the even numbers. for (int counter = 1 ; counter <= MAX;) { input = bfr.readLine(); loopNum = Integer.parseInt (input); cube = (counter * counter * counter); input = bfr.readLine(); even_product = Integer.parseInt (input); System.out.print (counter + " " + product + " " + cube); } fr.close(); } } inside the squares.txt file: 0 0 2 4 4 16 6 36 8 64 10 100 12 144 14 196 16 256 18 324 20 400 22 484 24 576 26 676 28 784 30 900 32 1024 34 1156 36 1296 38 1444 40 1600 42 1764 44 1936 46 2116 48 2304 50 2500 I dont know why this prgram will not run I have tried everything I can think of but it still wont work ![]() |
Author: | Tony [ Thu Mar 11, 2010 1:11 am ] |
Post subject: | RE:Program wont run |
If there's an exception, it's typically printed out. What does it say? (Or in what other way does the program "not run"?) |
Author: | chrisbrown [ Thu Mar 11, 2010 1:42 am ] |
Post subject: | RE:Program wont run |
for (int counter = 1 ; counter <= MAX;) I believe you want "counter++" after the semicolon? |
Author: | Tony [ Thu Mar 11, 2010 2:48 am ] | ||
Post subject: | RE:Program wont run | ||
That's not necessary; consider the
construct. The program should still execute, although the logical error might produce an undesirable result. |
Author: | chrisbrown [ Thu Mar 11, 2010 7:57 pm ] |
Post subject: | RE:Program wont run |
Good point Tony, forgot about that. There are a couple of issues: input = bfr.readLine(); readLine reads until a newline, so should be called only once per line. In your case, input would have the value "0 0", not "0". That isn't a parseable integer, so you will get an exception on this line: loopNum = Integer.parseInt (input); After that is taken care of, you need to keep track of what line you're on or else you will read past the end of the file and the program will crash. See my other post for details. |