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?
Related
I have a program that contains five .txt files. These files are read in and put into different arrays. One is an array of names. The other four are arrays with test scores.
Currently, the program does create the arrays correctly. Next the program is to calculate and display the average for each test (this works fine). Then the program prompts the user for a name. If a name is found a new menu will prompt the user to select which test they want the data on. (This works fine).
The problem: I have the main program class and another GradeBook class (does calculations) on another page. How do I connect the two pages together?
For example: If the studentName is 'Andrew' and it is found in studentNameArray, and I select 1 for which test score I want to see (scoreOneArray), say the number 88. My program finds 'Andrew' and '88'. What it does not do is send 'Andrew' and '88' to GradeBook to have the data compute test percentage (88/100) and find the corresponding letter grade (in this case 'B'). Lastly, then print students name, test score (88%), and the letter grade.
Program (main):
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
double test1Calculation;
double test2Calculation;
double test3Calculation;
double test4Calculation;
int i, j, k, l;
int testOneSum = 0;
int testTwoSum = 0;
int testThreeSum = 0;
int testFourSum = 0;
int checker = 0;
int index=0;
String choice;
Scanner students = new Scanner(new File("names.txt"));
Scanner TestOne = new Scanner(new File("testOne.txt"));
Scanner TestTwo = new Scanner(new File("testTwo.txt"));
Scanner TestThree = new Scanner(new File("testThree.txt"));
Scanner TestFour = new Scanner(new File("testFour.txt"));
String token1 = "";
List<String> studentName = new ArrayList<>();
while (students.hasNext()) {
// find next line
token1 = students.next();
studentName.add(token1);
}
String[] studentNameArray = studentName.toArray(new String[0]);
List<Integer> scoreOne = new ArrayList<>();
// while loop
while (TestOne.hasNext()) {
// find next line
Integer token2 = TestOne.nextInt();
scoreOne.add(token2);
}
Integer[] scoreOneArray = scoreOne.toArray(new Integer[0]);
List<Integer> scoreTwo = new ArrayList<>();
// while loop
while (TestTwo.hasNext()) {
// find next line
Integer token3 = TestTwo.nextInt();
scoreTwo.add(token3);
}
Integer[] scoreTwoArray = scoreTwo.toArray(new Integer[0]);
List<Integer> scoreThree = new ArrayList<>();
// while loop
while (TestThree.hasNext()) {
// find next line
Integer token4 = TestThree.nextInt();
scoreThree.add(token4);
}
Integer[] scoreThreeArray = scoreThree.toArray(new Integer[0]);
List<Integer> scoreFour = new ArrayList<>();
// while loop
while (TestFour.hasNext()) {
// find next line
Integer token5 = TestFour.nextInt();
scoreFour.add(token5);
}
Integer[] scoreFourArray = scoreFour.toArray(new Integer[0]);
for (i = 0; i < scoreOneArray.length; i++)
testOneSum += scoreOneArray[i];
test1Calculation = (double) testOneSum / 5;
for (j = 0; j < scoreTwoArray.length; j++)
testTwoSum += scoreTwoArray[j];
test2Calculation = (double) testTwoSum / 5;
for (k = 0; k < scoreThreeArray.length; k++)
testThreeSum += scoreThreeArray[k];
test3Calculation = (double) testThreeSum / 5;
for (l = 0; l < scoreFourArray.length; l++)
testFourSum += scoreFourArray[l];
test4Calculation = (double) testFourSum / 5;
System.out.println("The average for test one is: " + test1Calculation);
System.out.println("The average for test two is: " + test2Calculation);
System.out.println("The average for test three is: " + test3Calculation);
System.out.println("The average for test four is: " + test4Calculation);
Scanner studentSearch = new Scanner(System.in);
System.out.println("Enter student name : ");
String foundStudent = studentSearch.nextLine();
boolean found = Arrays.stream(studentNameArray).anyMatch(t -> t.equals(foundStudent));
if (found) {
index++;
System.out.println(foundStudent + " is found.");
//menu loop
do {
//displayed user options
System.out.println("1. To find score for first test");
System.out.println("2. To find score for second test");
System.out.println("3. To find score for third test");
System.out.println("4. To find score for fourth test");
//menu choices
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter your choice: ");
choice = keyboard.next();
if (choice.equals("1")) {
int score= scoreOneArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("2")) {
int score= scoreTwoArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("3")) {
int score= scoreThreeArray[index];
System.out.println(score);
checker = -1;
} else if (choice.equals("4")) {
int score= scoreFourArray[index];
System.out.println(score);
checker = -1;
} else {
//Error message
System.out.println("invalid choice");
}
}
while (checker != -1);
} // End of Menu Method
else {
System.out.println(foundStudent + " is not found.");}
students.close();
TestOne.close();
TestTwo.close();
TestThree.close();
TestFour.close();
}
}
Calculations(GradeBook):
import java.util.ArrayList;
public class GradeBook {
private char[] letterGrade = {'A', 'B', 'C', 'D', 'F'};
private ArrayList<String> names = new ArrayList<>();
private double [][] scores = new double[5][4];
public GradeBook(ArrayList<String> studentNames, double[][] studentScores){
this.names = studentNames;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 4; j++){
scores [i][j] = studentScores[i][j];
}
}
}
public String getName(int studentIndex){
return names.get(studentIndex);
}
public double getAverage(int studentIndex){
double total = 0;
for (int i = 0; i < 4; i++){
total += scores[studentIndex][i];
}
return (total / 4);
}
public char getLetterGrade(double avgScore){
if (avgScore >= 90 && avgScore <= 100){
return letterGrade[0];
}
else if (avgScore >= 80 && avgScore <= 89){
return letterGrade[1];
}
else if (avgScore >= 70 && avgScore <= 79){
return letterGrade[2];
}
else if (avgScore >= 60 && avgScore <= 69){
return letterGrade[3];
}
else if (avgScore >= 0 && avgScore <= 59){
return letterGrade[4];
}
return ' ';
}
public void getStudent(){
for (int i = 0; i < names.size(); i++){
System.out.println("\nStudent #" + (i+1)
+"\n\t\tName: " + names.get(i)
+"\n\t\tAverage: " + getAverage(i) + "%"
+"\n\t\tLetter Grade: " + getLetterGrade(getAverage(i))
+"\n\n");
}
}
}
I don't understand how much of what's going on in GradeBook relates to what you're doing in your main function. I see how in your main you're coming up with a single score based on the user's selection of a student and a test number. But once you have this user and score, I don't see how that matches up with the data in the double[][] studentScores table contained in GradeBook. What is that data? Where does it come from?
Your code in main seems to have a significant problem. index will always be 1 by the time it's used. Its value is not affected by what is entered as a student name. I think you mean for it to be. Also, I don't understand how the single integer score you come up with in main matches up with the avgScore accepted by the GradeBook. But ignoring all of that...
It seems like you'd have just a single GradeBook, right? So I think you'd instantiate just a single instance of it, and then you could use it to look up the student's name and to calculate the grade based on the student's score. Assuming that index matched up with the names list in GradeBook, and you somehow computed an averageScore, that would look something like this...
public class Main {
public static void main(String[] args) throws IOException {
...
GradeBook gradeBook = new GradeBook(...);
...
while (...) {
index = ...
...
averageScore = ...
...
studentName = gradeBook.getName(index);
grade = gradeBook. getLetterGrade(averageScore);
System.out.println(String.format("Student: %s. Grade: %s", studentName, grade));
}
The other use case I can see is that you'd calculate somehow calculate the studentScores table from the data you read in main, and then you could create a GradeBook with that to have it display all of that information. That would look like this...
studentScores = ...
...
GradeBook gradeBook = new GradeBook(studentScores);
gradeBook.getStudent()
I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}
So when i i have tried to save and compile everything works fine until I run it. There seems to be an issue with my array syntax. Could someone help me find it?When I do run this program the grades()method outputs "AAA" . What I'm trying to do in this program is read text from a txt file and list each line, outputting a student name and score. Now in the grades() method I am trying to output calculate a letter grade for each of the students grades and make that go into a loop until the last score has been read.
public class ReadData
{
private static String[] names = new String[3];
private static int line;
private static int[] scores = new int[3];
private static float mean;
private static double stdDeviation;
public static void readData() throws FileNotFoundException
{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
int l = 0;
// float sum = 0 ;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
names[l] = words[0];
scores[l] = Integer.parseInt(words[1]);
// sum+=scores[l];
System.out.println(" name: " + names[l] + ", score: " + scores[l]);
l++;
}
// System.out.println(scores[0]+ " " + scores[1]+ " " + scores[2]);
}
public static void fndMean()
{
float mean = ((25+65+89)/3);
System.out.println(" The mean is: " + mean);
}
public static void fndStandard() throws FileNotFoundException
{
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
System.out.println("The Standard Deviation is: " + stdDeviation);
}
Grades method
public static void grades()
{
for(int i = 0; i < (scores.length); i++)
{
if(mean + stdDeviation <= scores[i])
{
System.out.print("A");
}
else if( (scores[i] >= mean+(stdDeviation/3)) &&
(mean +stdDeviation)> scores[i])
{
System.out.print("B");
}
else if( (scores[i] >= mean-(stdDeviation/3)) &&
(mean +(stdDeviation/3))> scores[i])
{
System.out.print("C");
}
else if( (scores[i] >= mean-(stdDeviation)) &&
(mean - (stdDeviation/3))> scores[i])
{
System.out.print("D");
}
else
{
System.out.println("F");
}
}
}
You are re-declaring your variables in methods like fndMean() and fndStandard() when you do the following
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
float mean = ((25+65+89)/3);
You already declare them up top and don't need to do it again, otherwise it will only set the local variables inside the methods and not inside your class. you should do
stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
mean = ((25+65+89)/3);
Which will set those variables to what you were expecting when you call those methods BEFORE calculating the grades.
This is what fndMean and fndStandard methods print:
The mean is: 59.0
The Standard Deviation is: 26.407069760451147
Sum of mean and stdDeviation is 85.40706976045115.
Now, the condition if(mean + stdDeviation <= scores[i]) checks whether that sum is less than equal to score[i] and if yes, prints 'A'. It can be true in either of these two cases:
Values in second column (tab) in txt files are all more than 85
score array gets altered between two method calls
Printing score value before those conditions should give you some more idea.
I am a beginner in Java programming and I want to know : What does it mean by or it's function:
obtainedMarks = se.nextInt();
in this code :
package ifstatment;
import java.util.Scanner;
public class Ifstatment {
public static void main(String[] args) {
int obtainedMarks ;
int passingMarks;
String grade;
Scanner se = new Scanner(System.in);
System.out.println("Enter your scoor");
passingMarks = 40 ;
obtainedMarks = se.nextInt();
if (obtainedMarks >= passingMarks ){
if (obtainedMarks > 90)
grade = "A";
else if (obtainedMarks > 75)
grade = "B";
else if (obtainedMarks > 65)
grade = "C";
else
grade ="D";
System.out.println("You passed the exam and your grade is"+ grade);
} else {
grade = "F";
System.out.println("You failed in thee exam and your grade is " + grade);
}
}
}
You are reading an int from the console and saves it to the obtainedMarks variable.
You can read more about Scanner here
se.nextInt()
reads the next int value from the input stream (System.in in your case) and returns that value.
obtainedMarks = se.nextInt()
"takes" that value and assigns it to the variable obtainedMarks.
se.nextInt()
This mean that you will input an integer from console and assign it to var obtainedMarks
Please access this link for more information.
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);
}
}