Calculating gpa is returning error - java

Hy guys i will need a quick help with my asigment. I tryed to debug this code and i dont know how do i got this error but when i try to calculate gpa it is sending me 0 instead of value from switch.
If user is pressing A and credits 4 it needs to return 4 * 4 but for letter A i am receiving 0
public class Gpa{
private int sumOfCredits;
private int sumOfPoints;
private int points = 0;
public Gpa(){
sumOfPoints=0;
sumOfCredits=0;
}
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
case "A":
points = 4;
break;
case "B":
points = 3;
break;
case "C":
points = 2;
break;
case "D":
points = 1;
break;
case "F":
points = 0;
break;
case "a":
points = 4;
break;
case "b":
points = 3;
break;
case "c":
points = 2;
break;
case "d":
points = 1;
break;
case "f":
points = 0;
break;
default:
points = -1;
}
return points;
}
public int getSumOfCredits(){
return sumOfCredits;
}
public int getSumOfPoints(){
return sumOfPoints;
}
public void addToTotals(String grade,int credits){
sumOfCredits =+ credits;
calcPoints(grade);
sumOfPoints =sumOfPoints + points * credits;
}
public double calcGPA(){
double gpa = sumOfPoints /sumOfCredits;
return gpa;
}
}
and this is my tester class:
import java.util.*;
public class ComputeGpa {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Gpa gpaC = new Gpa();
for (int i = 1; i <= 3; i++) {
System.out.printf("Enter grade (one character): ");
String grade = scan.next();
System.out.printf("Enter credits: ");
int credits = scan.nextInt();
gpaC.addToTotals(grade, credits);
System.out.printf("Sum Points: %d", gpaC.getSumOfPoints());
System.out.printf("\tSum Credits: %d\n", gpaC.getSumOfCredits());
}
System.out.printf("GPA: %.2f", gpaC.calcGPA());
}
}

in your calcGPA() method you are doing integer division when you want to do floating division. You either have to cast the sumOfPoints variable or the sumOfCredits to a double.

double gpa = sumOfPoints /sumOfCredits;
Is integer division in java and will return an integer value. Chances are it is always a value between 0 and 1, which will be equivalent to 0 after being casted to an integer. See if casting them to double fixes it.
double gpa = (double)sumOfPoints / (double)sumOfCredits;
You are also redefining points on each loop here:
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
Which means that instead of changing the global variable points you are changing the local variable points. So you need to remove that local variable points so it uses the global one, also you dont need to return anything so just use void:
public void calcPoints(String grade) {
switch (grade) {
//cont

Related

My Basic Currency Converter program gives bad output

So, The code SHOULD convert currencies, but it doesn't do it correctly. I have a variable k(Croatian kuna... 1 EURO = 7.5 KUNA)which is 1 and for example, if I want to convert 1 euro to 1 dollar, the program multiplies the amount (1) by 7.5, then I have that amount of euros in KUNA, and that Works. But, when I go to divide that result (7.5) with 6.3(1 DOLLAR IS 6.3 KUNA), I get the same number.
import java.util.Scanner;
public class Conv {
private double rez;
private double rez2;
private double svota;
Scanner ul = new Scanner(System.in);
public void PretvorbaInKunu(double y) {
System.out.print("Insert amomunt: ");
svota = ul.nextDouble();
rez2 = svota*y;
}
public void PR2(double x) {
rez = getRez2() / x;
}
public double getRez() {
return rez;
}
public double getRez2() {
return rez2;
}
public double getSvota() {
return svota;
}
}
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch(iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch(u) {
case "e":
more.PR2(e);
case "d":
more.PR2(d);
case "p":
more.PR2(p);
case "k":
more.PR2(k);
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
}
}
The problem is in your second switch-case statement: You need to add a break at the end of every case.
If you change the class Vjezbica like this it should work:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch (iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch (u) {
case "e":
more.PR2(e);
break;//added break here
case "d":
more.PR2(d);
break;//added break here
case "p":
more.PR2(p);
break;//added break here
case "k":
more.PR2(k);
break;//added break here
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
//you should also close the scanner at the end...
in.close();
}
}
First of all - mistake was, as already pointed out by Tobias, the missing "break;"
But there are other mistakes in the code, e.g. Scanner is not closed.
I would also suggest to improve code quality. You could write an enum type that performs just calculation (no input - input should be separated). You can easily define currencies with different enum constructors then.
There was also discussion above if double or BigDecimal should be used. BigDecimal is an "expensive" type. I am wondering if float isn't enough, because currency values usually contain a precision of 2 digits - and if you are not dealing with very high amounts, a 32bit float type should already suffer.
I'd rewrite it as follows:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
private static enum Currency {
EURO(7.5), KUNA(1), DOLLAR(6.3), P(9.3);
private double cr;
Currency(double conversionRate) {
this.cr = conversionRate;
}
// precision: 2digits
public float fromKuna(double kuna) {
return (int) (((kuna) / cr) * 100) / 100f;
}
public float toKuna(double foreignCurrency) {
return (int) (((foreignCurrency) * cr) * 100) / 100f;
}
}
private static Currency readCurrency() {
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
in.close();
switch (iz) { // no break required when returning directly
case "e":
return Currency.EURO;
case "d":
return Currency.DOLLAR;
case "p":
return Currency.P;
case "k":
return Currency.KUNA;
default:
throw new IllegalArgumentException("invalid input: " + iz);
}
}
private static float readAmount() {
Scanner ul = new Scanner(System.in);
float svota = ul.nextFloat();
ul.close();
return svota;
}
public static void main(String[] args) {
System.out.print(" From ");
Currency c1 = readCurrency();
System.out.print("Insert amomunt: ");
float svota = readAmount();
float amountInKuna = c1.toKuna(svota);
System.out.print(" To ");
Currency c2 = readCurrency();
float amountInC2 = c2.fromKuna(amountInKuna);
System.out.println(svota + " " + c1.toString() + " is " + amountInC2 + " " + c2.toString());
}
}
Not considered: conversion does first convert from X to Kuna, and then from Kuna to Y. In both conversions, we are performing an inprecise rounding (flooring instead of correct rounding, and flooring twice instead of just once).
Based on this suggestion, it would be even better if you calculate a precise conversion rate which allows direct conversion from X to Y in the end, and you perform a round operation on the final result then.

GPA array calculation error

I am having issues with my gpa program where I have to use two arrays to store a grade and it's credits and calculate the gpa. So far, everything else seems to be working except the gpa wont calculate correctly and I am not sure what I am missing (probably simple).
My code thus far is:
Gpa class:
import java.util.*;
public class Gpa{
int[] credits = new int[4];
String[] grades = new String[4];
private int numCourses;
private int maxCourses;
private int sumOfCourses;
private int sumCredits;
private int sumPoints;
int newCredits;
int totalSum = 0;
int total = 0;
public Gpa(int noCourses){
maxCourses = noCourses;
numCourses = 0;
}
public void addCourse(int _newCredits, String newGrade){
for (int i=0; i<maxCourses; i++){
newCredits = _newCredits;
credits[i] = newCredits;
}
for (int i=0; i<maxCourses; i++){
grades[i] = newGrade;
}
switch (newGrade) {
case "A":
case "a":
newGrade = "4";
break;
case "B":
case "b":
newGrade = "3";
break;
case "C":
case "c":
newGrade = "2";
break;
case "D":
case "d":
newGrade = "1";
break;
case "F":
case "f":
newGrade = "0";
break;
}
sumPoints = sumPoints + (newCredits * Integer.parseInt(newGrade));
numCourses++;
}
public double calcGPA(){
for (int i=0; i<maxCourses; i++){
sumCredits = sumCredits + newCredits;
}
double gpa = (double)sumPoints/sumCredits;
return gpa;
}
} // end class
The tester class:
import java.util.Scanner;
public class GpaTestEx2
{
public static void main (String[] args)
{
//declarations
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa myGPA = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
myGPA.addCourse(credits, grade);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", myGPA.calcGPA( ));
} //end main
}
When I enter the course credits and grade it does not calculate the gpa correctly. For example, if the user input says there are 2 courses with one class having 4 credits with a grade of A and the other having 3 credits with a grade of B. I get a gpa of around 4.17 when it should be 3.57.
Any help would be great, I may or may not be missing something simple.
It seems like you are indexing into every element in your array every time someone inserts a value. We only need to change one element when a new grade is added. GPA class:
public class Gpa {
private int[] credits;
private String[] grades;
private int currentGrade;
public Gpa(int numGrades) {
credits = new int[numGrades];
grades = new String[numGrades];
currentGrade = 0;
}
public void addGrade(String letterGrade, int credit) {
grades[currentGrade] = letterGrade;
credits[currentGrade] = credit;
currentGrade = currentGrade + 1;
}
public double getGpa() {
double totalPoints = 0;
double totalWeight = 0;
for (int i = 0; i < currentGrade; i++) {
totalPoints = totalPoints + (letterToGpa(grades[i]) * credits[i]);
totalWeight = totalWeight + credits[i];
}
return totalPoints / totalWeight;
}
private double letterToGpa(String letter) {
char first = letter.toUpperCase().charAt(0);
switch (first) {
case 'A':
return 4.0;
case 'B':
return 3.0;
case 'C':
return 2.0;
case 'D':
return 1.0;
}
return 0.0;
}
}
The test class should work fine now:
public static void main(String[] args) {
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa t = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
t.addGrade(grade, credits);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", t.getGpa());
}
Just want to note that this clearly isn't the best way of doing this, nor does it follow Object Oriented patterns very well, but the OP's assignment requires we only use one class, etc.

Java - Displaying the temperature statistics of the week using arrays

I am currently working on a problem set for an assignment at school, and I'm really close to finishing however I'm getting a few compilation errors.
The problem set includes displaying the weeks avg. temp, highest temp., lowest temp., and the days of the week that are hottest and coldest.
Currently what I'm trying to do is display the days of the week that are hottest, and if I work that out I can easily find the coldest days of the week.
I'm getting a few compilation errors when I try to compile the code which includes
incompatible types: int[] cannot be converted to int
error: cannot find symbol
It would be great if I could get some guidance on what to do, I'm currently at lost right now.
http://ideone.com/rOqV2Z
public class test1
{
// Main method
public static void main(String[] args)
{
// Create a new scanner
Scanner input = new Scanner(System.in);
// Set array list
int[] tempList = new int[7];
// Prompt user for input and store input
System.out.println("Enter the hightest temperature of each day for a week (starting on Sunday): ");
for(int i = 0; i < tempList.length; i++)
tempList[i] = input.nextInt();
// Averages temperature - ####### ASK WHY IT THERE ARE SO MANY DECIMALS ON THE SIDE WHEN AVERAGE ALL 1's
double avgTemp = avgTemp(tempList);
System.out.printf("The average temperature of the week is: %.2f degree %n", avgTemp);
// Display hottest temperature
int maxTemp = maxTemp(tempList);
System.out.println("The highest temperature of the week is: " + maxTemp + " degree");
// Display coldest temperature
int minTemp = minTemp(tempList);
System.out.println("The coldest temperature of the week is: " + minTemp + " degree");
int[] maxTempList = searchTemp(tempList, maxTemp);
for(int i = 0; i < maxTempList.length; i++){
System.out.print("The hottest days of the week are: " +maxTempList[i]);
System.out.print(weekDay(tempList,maxTemp));
}
}
// Average the temperature
public static double avgTemp(int[] array)
{
int tempTotal = array[0];
// Total temperature values
for(int i = 0; i < array.length; i++)
tempTotal = array[i]+tempTotal;
// Return temperature average.
return ((double)tempTotal/array.length);
}
// Get hottest temperature
public static int maxTemp(int[] array)
{
int max = array[0];
// Check and replace max temp
for(int i = 1; i < array.length; i++){
if(max < array[i])
max = array[i];
}
return max;
}
// Get coldest temperature
public static int minTemp(int[] array)
{
int min = array[0];
for(int i = 1; i < array.length; i++){
if(min > array[i])
min = array[i];
}
return min;
}
// Return days
public static String weekDay(int i, int[] array)
{
int[] displayWeekDay = searchTemp(array, i);
for(i = 0; i < displayWeekDay.length; i++){
String weekDay = "";
switch(i)
{
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesdays";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
}
}
return weekDay;
}
// Finds the index of the hottest/coldest days
public static int[] searchTemp(int[] temp, int key)
{
int count = 0;
for(int i = 0; i < temp.length; i++){
if(temp[i] == key)
count++;
}
int[] index = new int[count];
for(int j = 0; j < index.length; j++){
for(int i = 0; i < temp.length; i++){
if(temp[i] == key){
if(j > 0 && index[j - 1] == i)
continue;
else{
index[j] = i;
break;
}
}
}
}
return index;
}
}
I went and checked the code using the website you linked.
Firstly, you should learn to use the debugger, as it will usually tell you what the error is and where to find it.
Main.java:42: error: incompatible types: int[] cannot be converted to int
System.out.print(weekDay(tempList,maxTemp));
^
Here it points to an error on the data type of tempList. It's saying that an int array cannot be converted to an int. If you look at the weekDay() function you'll see that the first argument is asking for an int, but you are passing an int array. It won't work.
public static String weekDay(int i, int[] array)
EDIT: If you want to pass a specific value into the function from the array just use
System.out.print(weekDay(tempList[IntegerPosition],maxTemp));
^
Main.java:104: error: cannot find symbol
return weekDay;
^
This simply means it can't find the variable in the current scope. There's a lot to learn about this, but I'll just get to the point.
// Return days
public static String weekDay(int i, int[] array)
{
int[] displayWeekDay = searchTemp(array, i);
String weekDay = "";
for(i = 0; i < displayWeekDay.length; i++){
//String weekDay = ""; Declare weekDay outside of the loop
switch(i)
{
//Assign a value to weekDay, simply returning won't do it
case 0: weekDay = "Sunday"; break;
case 1: weekDay = "Monday"; break;
case 2: weekDay = "Tuesday"; break;
case 3: weekDay = "Wednesdays"; break;
case 4: weekDay = "Thursday"; break;
case 5: weekDay = "Friday"; break;
case 6: weekDay = "Saturday"; break;
}
}
return weekDay;
}
EDIT 2: As per the discussion, this is what I would do in order to be able to print multiple days that had the highest temperature
//Call the function directly without putting a print statement around it
weekDay(maxTemp,tempList));
//...
// Return days
public static void weekDay(int i, int[] array) //Change the return type to void
{
int[] displayWeekDay = searchTemp(array, i);
for(i = 0; i < displayWeekDay.length; i++){
switch(displayWeekDay[i])
{
//Print each one
case 0: System.out.println("Sunday"); break;
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
}
}
}
Addressing each issue on it's own:
"incompatible types: int[] cannot be converted to int" issue
This is being caused by the line System.out.print(weekDay(tempList,maxTemp));. The method signature for the weekDay method is public static String weekDay(int i, int[] array) however the method is being called with arguments in the wrong order - tempList is of type int[] and maxTemp is of type int. Reversing the arguments in either the method call or the method signature will resolve the error.
"error: cannot find symbol"
This is an issue related to variable scope. When a variable is declared (e.g. int i; or String name = "John";), that variable can only be used within the scope that it is declared in. In the weekDay method the weekDay variable is declared inside the for loop (i.e. inside of the braces associated with the for loop). As such the weekDay variable only has the scope of the for loop, and cannot be referenced outside of that scope. Moving the declaration of weekDay outside of the for loop will fix the issue. See here for more information on variable scope rules.
Like I said, think about the API first, input later. This implementation assumes JDK 8 and lambdas:
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* Created by Michael
* Creation date 3/19/2016.
* #link https://stackoverflow.com/questions/36107614/java-displaying-the-temperature-statistics-of-the-week-using-arrays
*/
public class TemperatureHistory {
private Map<Date, Double> temperatureHistory = new TreeMap<>();
public void addDataPoint(Date date, Double temperature) {
if (date != null && temperature != null) {
this.temperatureHistory.put(date, temperature);
}
}
public Double getAverageTemperature() {
double averageTemperature = 0.0;
if (this.temperatureHistory.size() > 0) {
averageTemperature = this.temperatureHistory.values()
.stream()
.collect(Collectors.averagingDouble(value -> value));
}
return averageTemperature;
}
public Double getMaxTemperature() {
return this.temperatureHistory.entrySet()
.stream()
.max((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
.get()
.getValue();
}
public Double getMinTemperature() {
return this.temperatureHistory.entrySet()
.stream()
.min((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
.get()
.getValue();
}
public Date getFirstDateForTemperature(Double temperature) {
return this.temperatureHistory.entrySet()
.stream()
.filter(e -> e.getValue().equals(temperature))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
public Date getDateMinTemperature() {
return this.getFirstDateForTemperature(this.getMinTemperature());
}
public Date getDateMaxTemperature() {
return this.getFirstDateForTemperature(this.getMaxTemperature());
}
}
In the last statement of you main method you do System.out.print(weekDay(tempList,maxTemp));
weekDay takes an int as the first argument, but tempList is of type int[]. You should swap the order of tempList and maxTemp either in your method call or definition.
public static String weekDay(int i, int[] array)
In this method, you're suppose to return a String type value
edit: change the string variable to other name. you can't have it the same as the method's name

Bracket expected.... not sure where [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().

Need assignment idea

I need help with my assignment.I need to write class program that tranlates grade into grade point. If the grade have + like A+ it will increase the grade point by 0.3 and - will decrease by 0.3.
private static final double GradePoint = 0;
private static Scanner input;
public static void main(String [] args)
{
String grade ;
double GradePoint = 0;
System.out.print("Please enter your grade: ");
input = new Scanner(System.in);
grade = input.nextLine();
switch(grade)
{
case "A":
case "a": GradePoint = 4; break;
case "B":
case "b": GradePoint = 3; break;
case "C":
case "c": GradePoint = 2; break;
case "D":
case "d": GradePoint = 1; break;
case "F":
case "f": GradePoint = 0; break;
}
System.out.print("Your grade is: "+GradePoint);
}
public double getGradePoint(String grade)
{
return GradePoint;
}
What i dont understand is about how to use the method to calculate.I'm still beginner.
I have to use CLASS and method*public double getGradePoint(String grade)* to
return the grade point of grade entered.
You need to shift your entire code from main() to getGradePoint(String grade);
also your switch case switch(grade) will not work for values like "A+" as there are no such case that matches the string "A+"
I was bored and had nothing better to do so here :)
public class GradeCalculator
{
public static void main(String[] args)
{
System.out.print("Please enter your grade: ");
Scanner input = new Scanner(System.in);
String grade = input.nextLine().trim();
GradeCalculator calculator = new GradeCalculator();
double gradePoint = calculator.getGradePoint(grade);
System.out.print("Your grade is: " + gradePoint);
}
private double getGradePoint(String grade)
{
int score = getGradeScore(grade.charAt(0));
double modifier = 0;
if (grade.length() > 1)
{
modifier = getModifierValue(grade.charAt(1));
}
return score + modifier;
}
private int getGradeScore(char grade)
{
int score = 0;
switch (grade)
{
case 'A':
case 'a':
score = 4;
break;
case 'B':
case 'b':
score = 3;
break;
case 'C':
case 'c':
score = 2;
break;
case 'D':
case 'd':
score = 1;
break;
case 'F':
case 'f':
score = 0;
break;
}
return score;
}
private double getModifierValue(char modifier)
{
double value = 0;
switch (modifier)
{
case '+':
value = 0.3;
break;
case '-':
value = -0.3;
break;
}
return value;
}
}

Categories

Resources