|
-
May 24th, 2005, 11:33 PM
#1
Q's regarding double/float initialization
I've been programming with Java for quite some time but there's this one among other things that I couldn't find an answer for...
****************************************
import java.io.*;
public class GPA {
public static void main(String a[])throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in)) ;
double gpaInput[] = new double[4];
double gpaTot = 0;
for(int ctr = 0; ctr< gpaInput.length; ctr++) {
System.out.println("Input Grade:");
gpaInput[ctr] = Double.parseDouble(input.readLine());
gpaTot += gpaInput[ctr];
}
gpaTot /= gpaInput.length;
System.out.println("Average grade is: " + gpaTot);
}
}
*********************************
The particular code above doesn't seem to have any compiler error, but when I compile I get this:
Unexpected Signal : EXCEPTION_FLT_DIVIDE_BY_ZERO occurred at PC=0x137BEA8
Function=[Unknown.]
Library=(N/A)
NOTE: We are unable to locate the function name symbol for the error
just occurred. Please refer to release documentation for possible
reason and solutions.
Current Java thread:
Dynamic libraries:
0x7CC00000 - 0x7CC1D000 C:\WINDOWS\SYSTEM\IMAGEHLP.DLL
Local Time = Tue May 24 20:31:45 2005
Elapsed Time = 4
#
# HotSpot Virtual Machine Error : EXCEPTION_FLT_DIVIDE_BY_ZERO
# Error ID : 4F530E43505002D5
# Please report this error at
# http://java.sun.com/cgi-bin/bugreport.cgi
#
# Java VM: Java HotSpot(TM) Client VM (1.4.0_02-b02 mixed mode)
#
# An error report file has been saved as hs_err_pid4293351765.log.
# Please refer to the file for further information.
#
To correct the error, I simply change the way gpaTot was initialized:
double gpaTot = 1;
Or, I could make larger alterations by creating an object instead, which is more correct, i know.
****************************************
import java.io.*;
public class GPA {
double gpaInput[] = new double[4];
double gpaTot;
public static void main(String a[])throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in)) ;
GPA main = new GPA();
for(int ctr = 0; ctr< main.gpaInput.length; ctr++) {
System.out.println("Input Grade:");
main.gpaInput[ctr] = Double.parseDouble(input.readLine());
main.gpaTot += main.gpaInput[ctr];
}
main.gpaTot /= main.gpaInput.length;
System.out.println("Average grade is: " + main.gpaTot);
}
}
****************************************
It makes me wonder why it happens. I couldn't find the answers on books...they only mentioned that variables have default values but under "some circumstances" they must still be initialized(for local variables). Nobody warned me that i can't initialize double/float to zero (0).
I used jdk1.4.0_02 for the above code. I'll be upgrading it when I have the time.
tnx in advance.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|