I'm new to programming, especially in Java, so please bear with what may be a very noob-ish question. My main goal here is to create a simple program that calculates the user's GPA by taking three character inputs and displaying the result as a double. For this program I was only required to represent basic letter grades (no A+ or A- or anything like that, just A-F) with their corresponding numerical value (4.0-0.0).
I was able to get the program to work however my question lies in the way that I had to convert, or more so associate, the user's input into/with a decimal.
My approach to this, as you can see in the code below, was to have a user input their letter grade, create a separate variable that would hold the numerical value of each character for each class and use if statements in order to associate that value with it's corresponding character in it's corresponding class. Although it seems to work okay, is there a more efficient way of doing this? I found the if statements sort of inefficient as it seems like a lot of code for what I'm trying to accomplish.
Also, on a side note, I'm using Eclipse as my main IDE for Java and I keep on getting the yellow warning squiggly line message under the first "in" when I type "Scanner in = new Scanner(System.in);" It says "Resource leak: 'in' is never closed" and I have no idea what that means. My programs always run but I hate seeing the warning sign on my files in the package explorer :/
* Lab9.java
package labs;
import java.util.Scanner;
public class Lab9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Please input 3 letter grades: ");
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
char class1 = in.next() .charAt(0);
char class2 = in.next() .charAt(0);
char class3 = in.next() .charAt(0);
double g1 = 0, g2 = 0, g3 = 0;
if (class1 == 'A') {
g1 = 4.0;
}
if (class1 == 'B') {
g1 = 3.0;
}
if (class1 == 'C') {
g1 = 2.0;
}
if (class1 == 'D') {
g1 = 1.0;
}
if (class1 == 'F') {
g1 = 0.0;
}
if (class2 == 'A') {
g2 = 4.0;
}
if (class2 == 'B') {
g2 = 3.0;
}
if (class2 == 'C') {
g2 = 2.0;
}
if (class2 == 'D') {
g2 = 1.0;
}
if (class2 == 'F') {
g2 = 0.0;
}
if (class3 == 'A') {
g3 = 4.0;
}
if (class3 == 'B') {
g3 = 3.0;
}
if (class3 == 'C') {
g3 = 2.0;
}
if (class3 == 'D') {
g3 = 1.0;
}
if (class3 == 'F') {
g3 = 0.0;
}
System.out.print("Your GPA is a "+((g1 + g2 + g3)/3));
}
}
Here is the output of a test run:
Please input 3 letter grades: A C B
Your GPA is a 3.0
Thank you for the help!