How do I allow my method to read my main - java

import java.util.Scanner;
public class EP55Out
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
// getNumericGrade(grade);
}
public static void getNumericGrade(double grade)
{
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}
I don't know if you guys understand what I mean, but I keep getting the error that "grade" does not exist even though it is defined in the main. I know it has something to do with "void" but I have no clue what. Can anybody help?

So you are learning Java don't you?
I'll try to explain what you are doing wrong.
import java.util.Scanner;
public class EP55Out {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
//You need to give letter to the method
getNumericGrade(letter);
}
//AND the method should need String and not double
public static void getNumericGrade(String letter){
//After this you need a real double value - lets call is grade;
double grade = 0;
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
//You cant to numeric stuff with a String- thats why we use our double here
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade+"");
}
}
You missed an important point with variables...
If you define a variable in a method - it is only visible in THE DEFINING METHOD!
So
public static void getNumericGrade(String letter)
cannot know that there is a letter variable in
public static void main(String[] args)
Hope I could help you ;)

If I understood correctly, and If u r getting error on the line that u have commented...
then "grade" really does not exist, The name of variable is "letter"
can u plz try running this code and see if it works.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
String letter = in.next();
getNumericGrade(letter);
}
public static void getNumericGrade(String letter)
{
int spacer = 0;
double grade;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}

grade is not defined in main. What you are looking for is letter,
String letter = in.next();
getNumericGrade(letter);
However, this will not solve your problem, as the getNumericGrade method requires you to pass it a double. I think (based on the method name), that you really want getNumericGrade to accept a String, and return a double. I would try referring to your textbook or tutorial some more, as you haven't grasped methods quite yet I don't think.
In particular, the void means that a method doesn't return a value. void can be replaced with any type, like int or String or even SomeClass. On the same line, inside the parentheses is where you specify what arguments your method will accept. These can be of any type, and you can name them anything you want, they don't have to correspond to the names of the variables you pass to a method call. So, if I had a method getAverageGrade which accepted a String argument (say the name of a student) and returned a double which is the current average grade for that student, the method signature, or definition would look something like this
public double getAverageGrade(String studentName)
Hopefully that should get you started down the right path.

i think you should do like this way
import java.util.Scanner;
public class EP55Out
{
String letter = "";
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a grade: ");
letter = in.next();
getNumericGrade();
}
public static void getNumericGrade()
{
if(letter.length()<=0)
return;
int spacer = 0;
String first = letter.substring(0,1);
String second = letter.substring(1,2);
if (first.equalsIgnoreCase("a"))
grade = 4.0;
else if (first.equalsIgnoreCase("b"))
grade = 3.0;
else if (first.equalsIgnoreCase("c"))
grade = 2.0;
else if (first.equalsIgnoreCase("d"))
grade = 1.0;
else if (first.equalsIgnoreCase("f"))
grade = 0;
else grade = 9;
if (second.equalsIgnoreCase("+"))
grade += 0.3;
else if (second.equalsIgnoreCase("-"))
grade -= 0.3;
else
grade += 9;
System.out.println(grade);
}
}

Related

How can I take input as a string and convert to an integer stored in a seperate class?

I am trying to have the user input a letter grade and then convert it to an integer that is stored in a separate public class. I used several if loops to try to make this happen, but I can't get it to work. Any ideas what I am doing wrong and how to fix or work around it? When I run the code how it is now, all I can get for output is 0. I have a feeling that this is probably because I am trying to store the value in a separate class, but I don't know how to make it work.
import java.util.Scanner;
class Courses {
static public String letterGrade;
static public int numberGrade;
static public int creditValue;
static public float GPA;
}
public class GradeCruncher {
static Scanner userinput = new Scanner(System.in);
public static void main(String[] args) {
int numOfCourses;
int courseNum = 0;
System.out.println("How many courses would you like to input?");
numOfCourses = userinput.nextInt();
Courses[] course = new Courses[numOfCourses];
while (courseNum < numOfCourses) {
System.out.println("Enter info for course " + courseNum);
System.out.println("How many credits is this course worth?");
course[courseNum].creditValue = userinput.nextInt();
System.out.println("What is your current letter grade for this course?");
userinput.next();
course[courseNum].letterGrade = userinput.nextLine();
String aPlus = "a+", a = "a", aMinus = "a-", bPlus = "b+", b = "b", bMinus = "b-", cPlus = "c+", c = "c",
cMinus = "c-", dPlus = "d+", d = "d", dMinus = "d-", f = "f";
if (f.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 0;
}
else if (dMinus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 60;
}
else if (d.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 63;
}
else if (dPlus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 67;
}
else if (cMinus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 70;
}
else if (c.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 73;
}
else if (cPlus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 77;
}
else if (bMinus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 80;
}
else if (b.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 83;
}
else if (bPlus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 87;
}
else if (aMinus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 90;
}
else if (a.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 93;
}
else if (aPlus.equalsIgnoreCase(Courses.letterGrade)) {
course[courseNum].numberGrade = 100;
}
System.out.println(course[courseNum].numberGrade);
courseNum++;
continue;
}
System.out.println(course[courseNum].numberGrade);
Courses.GPA = ((course[0].numberGrade * course[0].creditValue) + (course[1].numberGrade * course[1].creditValue)) / (course[0].creditValue + course[1].creditValue);
System.out.println(Courses.GPA);
}
}
I have found several issues in your code, besides the things already stated in the comments:
Although you create an array of Courses, you never actually create any Courses objects, which you add to the array. When there are no Courses in your array, you also cannot assign your variables.
You should use a Map to avoid having to use all of these ifs.
The naming of your class is misleading. The array should be called courses and the class should be called Course.
I tried to rebuild your code so that it makes sense to me and works as I think it should.
import java.util.HashMap;
import java.util.Scanner;
class Course {
public String letterGrade;
public int numberGrade;
public int creditValue;
//public float GPA; // this should not be part of your Course class
Course(int credits, int gradeNum, String gradeLet) {
letterGrade = gradeLet;
numberGrade = gradeNum;
creditValue = credits;
}
}
public class GradeCruncher {
static Scanner userInput = new Scanner(System.in);
static HashMap<String, Integer> gradeMap = getGradeMap();
public static void main(String[] args) {
int numOfCourses;
int courseNum = 0;
System.out.println("How many courses would you like to input?");
numOfCourses = userInput.nextInt();
// create the array to store the courses
Course[] courses = new Course[numOfCourses];
// loop to get all courses
for (; courseNum < numOfCourses; courseNum++) {
System.out.println("Enter info for course " + courseNum);
System.out.println("How many credits is this course worth?");
// Get the credits for this course from input and save it temporarily
int tempCredits = userInput.nextInt();
System.out.println("Credits is " + tempCredits);
System.out.println("What is your current letter grade for this course?");
// this is needed so that the scanner removes the newline (\n) from the input
userInput.nextLine();
// Get the letter grade for this course from input and save it temporarily
String tempLetterGrade = userInput.nextLine();
System.out.println("Letter grade is " + tempLetterGrade);
// Retrieve the number grade from the map and save it
int tempNumberGrade = gradeMap.get(tempLetterGrade);
// Create the Course object with the input values and save it in the courses array
courses[courseNum] = new Course(tempCredits, tempNumberGrade, tempLetterGrade);
}
// All courses built
// Calculate GPA
double gpa = 0.0;
int overallCreditValue = 0;
for (int i = 0; i < courses.length; i++) {
gpa += (courses[i].numberGrade * courses[i].creditValue);
overallCreditValue += courses[i].creditValue;
}
gpa = gpa / overallCreditValue;
System.out.println("GPA Calculated: " + gpa);
}
private static HashMap<String, Integer> getGradeMap() {
HashMap<String, Integer> gradeMap = new HashMap<String, Integer>();
gradeMap.put("a+", 100);
gradeMap.put("a", 93);
gradeMap.put("a-", 90);
gradeMap.put("b+", 87);
gradeMap.put("b", 83);
gradeMap.put("b-", 80);
gradeMap.put("c+", 77);
gradeMap.put("c", 73);
gradeMap.put("c-", 70);
gradeMap.put("d+", 67);
gradeMap.put("d", 63);
gradeMap.put("d-", 60);
gradeMap.put("f", 0);
return gradeMap;
}
}
Explanation:
The letter and number grades are mapped in a map. The Course Class is now structured, so that the contents are input via the constructor. First all the inputs are retrieved from the user for each course and stored temporarily. When all the course info is retrieved, the Course object is created with this information and then stored in the courses array. When all courses are created, the average is calculated (according to the way you did it) and printed to the output.
Input and output:
How many courses would you like to input?
2
Enter info for course 0
How many credits is this course worth?
5
What is your current letter grade for this course?
a+
Enter info for course 1
How many credits is this course worth?
5
What is your current letter grade for this course?
a
GPA Calculated: 96.5
(f.equalsIgnoreCase(Courses.letterGrade)) ----- is wrong.
Replace Courses.letterGrade with Course[coursenum].lettergrade
remove continue,no need of that .
better design is to use switch statement.
Courses is a Class not a object u cannot store in it. You have created a object of type Courses 'courses' in this u can store.
replace Courses.Gpa to a integer variable.

calling methods, parameters and arguments

This is probably a dumb question. My following code looks fine but on the output, it does not expect results from my testing scenarios. Code follows:
import java.util.Scanner;
public class PartyPlannerLab {
public static Scanner input = new Scanner(System.in);
public static int getGuestCount(int guests) {
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson(int slicesPerPerson) {
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests, double roomCost) {
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(double sodaCost, int guests) {
sodaCost = guests * 1.50;
return sodaCost;
}
public static void printSummary(int guests, double roomCost, double sodaCost, double pizzaCost) {
System.out.println("Total Guests: " + guests);
System.out.println("RoomCost: $" + roomCost);
System.out.println("SodaCost: $" + sodaCost);
System.out.println("PizzaCost: $" + pizzaCost);
System.out.println("Total Cost: $" +(roomCost + sodaCost + pizzaCost));
}
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
getGuestCount(guests);
getSlicesPerPerson(slicesPerPerson);
computeRoomCost(guests, roomCost);
computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
}
One output is as follows:
Enter number of guests: 10
Enter number of slices per person: 2
Total Guests: 0
RoomCost: $0.0
SodaCost: $0.0
PizzaCost: $0.0
Total Cost: $0.0
You are not making use of the return values of getGuestCount, getSlicesPerPerson etc.
Those methods return a value, which basically means that you can use them as if they are a value. input.nextInt returns a value too, which is why you can put it on the right of =.
Inside the method, getGuestCount seems to change the value of guests passed in, but this change won't actually reflect on the caller's side, because Java is pass-by-value. You are kind of throwing away the value that was passed in.
In fact, your methods will only work as they are if the arguments are passed by reference, so that the methods can modify the variables passed in. But this is not possible in Java. See this post for the difference between pass-by-value and pass-by-reference.
The right way to rewrite your methods in Java is to return the value (which they are already doing, but you are not making use of the return value), and remove the extraneous parameter.
public static int getGuestCount() {
int guests;
while(true) {
System.out.print("Enter number of guests: ");
guests = input.nextInt();
if (guests >= 1 && guests <= 100)
break;
else
System.out.println("The guest count must be at least 1, but does not exceed 100. Please enter again.");
}
return guests;
}
public static int getSlicesPerPerson() {
int slicesPerPerson;
while(true) {
System.out.print("Enter number of slices per person: ");
slicesPerPerson = input.nextInt();
if (slicesPerPerson >= 1 && slicesPerPerson <= 8)
break;
else
System.out.println("The pizza slice count must be at least 1, but does not exceed 8. Please try again.");
}
return slicesPerPerson;
}
public static double computeRoomCost(int guests) {
double roomCost;
if (guests <= 30)
roomCost = 100.00;
else
roomCost = 200.00;
return roomCost;
}
public static double computeSodaCost(int guests) {
double sodaCost = guests * 1.50;
return sodaCost;
}
This is how you "make use of the return values": instead of passing in the variable you want the method to modify, put it on the left hand side of = in an assignment statement:
guests = getGuestCount();
slicesPerPerson = getSlicesPerPerson();
roomCost = computeRoomCost(guests);
sodaCost = computeSodaCost(guests);
The reason why you are not getting the output is that the values that you initialized in your main method are not being updated with the method calls you are making.
Below code might solve the problem you are facing -
public static void main(String[] args) {
int guests = 0;
int slicesPerPerson = 0;
double roomCost = 0.0;
double sodaCost = 0.0;
double pizzaCost = 0.0;
guests = getGuestCount(guests);
slicesPerPerson = getSlicesPerPerson(slicesPerPerson);
roomCost = computeRoomCost(guests, roomCost);
sodaCost = computeSodaCost(sodaCost, guests);
printSummary(guests, roomCost, sodaCost, pizzaCost);
input.close();
}
Note- There is no need of passing the parameter in the methods getGuestCount & getSlicesPerPerson as the input is being taken from I/O

if char equals a letter then execute a code

Please help I cannot run this block of code:
import java.util.Scanner;
public class Methods_in_java {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize = true;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
charAt is zero based.
You should use ab.charAt(0) if you use only a single char.
Another good advice is to start method names with a lower case and use the camelCase format.
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:
char fir = Character.toUpperCase(ab.charAt(0));
You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.
and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.
Just change your code to:
public class cn {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize=false;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(0));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
It would be helpful if you elaborated more on what your problem is,
do you have a run time error, a compile time error, or it the output just not what you'd expect.
Your problem may be that arrays start at 0 so the first letter is charAt(0).
Actually I believe another user mentioned that the prize variable was initialized to true. I believe that that is the issue and that answer should be marked correct.

Calling void methods from main method, cannot pass arguments within void methods

my teacher asked us to create an additive prime program for my computer science class. I have created all my void methods, and believe to have all the math logic figured out. However, when I try to pass arguments into the instances of my methods within my main method, It gives me an error saying:
it can not find the variable in this case variable 'x'
package additiveprimes;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author talarik048
*/
public class AdditivePrimes {
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public void userInput(String x){
Scanner sc = new Scanner(System.in);
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
}
public void isPrime(String x){
this.userInput(x);
boolean prime = true;
int y = Integer.parseInt(x);
for(int i = 0; i < y; i++){
if(y % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is prime...");
} else {
System.out.println("Your number is not prime...");
}
}
}
public void numArray(String x){
this.userInput(x);
String[] strArray = x.split("\\s+");
boolean prime = true;
int[] numbArray = new int[strArray.length];
for(int j = 0; j < strArray.length; j++){
try{
numbArray[j] = Integer.parseInt(strArray[j]);
} catch(NumberFormatException e){
System.out.println("ERROR");
}
for(int i = 0; i < numbArray.length; i++){
int sum = (Arrays.stream(numbArray).sum());
if(sum % i == 0){
prime = false;
break;
}
if(prime){
System.out.println("Your number is an additive prime...");
} else {
System.out.println("Your number is not an additive prime...");
}
}
}
}
}
I think you wanted to RETURN a value from userInput:
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(Exception e){// see OH GOD SPIDERS comment
System.out.println("Error, try again: ");
x = sc.nextLine();//this is not a good way for a retry
}
return x;
}
Alternatively you could make x a field.
Your methods accept a string as an argument, but you have not passed any. You need to initialize x in main.
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x= "55";
additivePrime.userInput(x);
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
Note
Although the above code fixes your current issue. It doesn't seem to be the correct way to use this class. You should probably be calling .userInput() method and getting the userInput then passing it to your other methods.
You could probably change your overall class to
public static void main(String[] args){
AdditivePrimes additivePrime = new AdditivePrimes();
String x = additivePrime.userInput();
additivePrime.isPrime(x);
additivePrime.numArray(x);
}
public String userInput(){
Scanner sc = new Scanner(System.in);
String x = null;
try{
System.out.println("Please enter a number: ");
x = sc.nextLine();
} catch(NumberFormatException e){
System.out.println("Error, try again: ");
x = sc.nextLine();
}
return x;
}
You have not defined x as anything before using it. Try defining x. In this case since your arguments are strings, I recommend...
String x = new String();

Why doesn't my program call my methods?

java methods statithing but I can't seem to get my while statement on line 56 to call my methods properly. Is there something that I'm doing wrong? I am very new to Java so any sort of help would be appreciated! Thanks in advance!
Here is my code:
import java.util.*;
import javax.swing.*;
import java.io.*;
public class GradeCalculator {
static String fileInput;
static double totalGrade;
static int scoreCount= 0;
static double classAverage;
static double score;
static double testScore;
static double averageScore;
static int numberOfStudents = 0;
static char letterGrade;
static String fileOutput;
static String nameOfStudent;
static int numberCount;
static int numberCalculatedStudents;
static double average = 0;
public static void main (String[] args) throws FileNotFoundException {
//Welcome
JOptionPane.showMessageDialog(null,"Welcome to the Grade Calculator! This program will\n" +
" calculate the average percentage of 5 test scores that\n"+
" are given in a given file once these scores are\n"+
" averaged it will give the student a letter grade.","Welcome!",JOptionPane.PLAIN_MESSAGE);
fileInput = JOptionPane.showInputDialog(null, "Please enter the name of the input file you wish to use for this program."
,"Input File",JOptionPane.PLAIN_MESSAGE);
fileOutput = JOptionPane.showInputDialog(null, "Please enter the name of the output file you wish to use for this program."
,"Output File",JOptionPane.PLAIN_MESSAGE);
//preparing text files
PrintWriter outFile = new PrintWriter (fileOutput);
File inFile = new File (fileInput);
Scanner reader = new Scanner(new FileReader(fileInput));
outFile.println("Student Name Test1 Test2 Test3 Test4 Test5 Average Grade");
while(reader.hasNextLine()) {
nameOfStudent = reader.next();
outFile.printf("%n%n%s",nameOfStudent);
numberOfStudents++;
score = reader.nextDouble();
calculateAverage(score);
calculateGrade(averageScore);
outFile.printf(" %.2f ", averageScore);
outFile.println(" "+letterGrade);
}
classAverage = classAverage/numberCalculatedStudents;
outFile.print("\n\n\n\n\n\n\n\n\n\n\n\nClass average for "+ numberCalculatedStudents + "of" + numberOfStudents + "is" + classAverage);
JOptionPane.showMessageDialog(null,"The report has successfully been completed and written into the file of " + fileOutput +"."
+" The class average is " + classAverage + ". Please go to the output file for the complete report.");
outFile.close();
}
public static void calculateAverage(double score) throws FileNotFoundException {
Scanner reader = new Scanner(new FileReader(fileInput));
PrintWriter outFile = new PrintWriter (fileOutput);
while (reader.hasNextDouble() && numberCount <= 5 ) {
score = reader.nextDouble();
numberCount++;
if (score >= 0 & score <= 100) {
outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);
}
if (average!=0){
numberCalculatedStudents++;
average = average/scoreCount;
averageScore = average;
classAverage = average + classAverage;
}
average = 0;
}
public static char calculateGrade (double averageScore) {
if (averageScore >= 90 && averageScore <= 100)
letterGrade = 'A';
else if (averageScore < 90 && averageScore >= 80)
letterGrade = 'B';
else if (averageScore < 80 && averageScore >= 70)
letterGrade = 'C';
else if (averageScore < 70 && averageScore >= 60)
letterGrade = 'D';
else if (averageScore < 60 && averageScore >= 0)
letterGrade = 'F';
else
letterGrade =' ';
return letterGrade;
}
}
Without knowing what line the problem is arising on, two issues jump out at me:
At the top of the while loop:
if (score >= 0 & score <= 100)
{ outFile.printf("%10.2f",score);
scoreCount++;
average = score + average;
}
else
outFile.printf(" **%.2f",score);}
You have a close bracket (}) after the else statement, but no open bracket. So that close bracket looks like its exiting the while loop before you want it to.
Second, it looks like you're trying to return something (namely a char) in your CalculateGrade method, but you have specified a return type of void on it, which means that even though you have a return statement, nothing gets returned when you call it. You don't show where you're calling that method, so I can't be sure this is causing a problem, but its certainly suspect. It seems like you want to use:
public static char calculateAverage(double score) throws FileNotFoundException{
instead of public static void calculateAverage(double score)...
Also, is there a reason why all of these methods are static? Do you know what making something static means?
EDIT (based on your comment):
No. making a variable static makes it a "class variable", which means that only one of them exists for all objects of that class. To illustrate:
If you have a class like this:
class test {
static int id;
}
And you run the following code:
test t1 = new test();
test t2 = new test();
t1.id = 4;
t2.id = 8;
System.out.println(t1.id);
it will print 8. This is because, since id is a static variable changing it on any object of the class will cause it to change for every other object of the class.
This is as opposed to an "instance variable" one of which exists for every object of the class. To make id an instance variable, simply remove the static keyword. If you do so and run the same code, it will print 4, because changing an instance variable of t2 has no effect on t1.
Make sense?

Categories