right now I am working on a program that is printing out a students name, id number, scores on exams, average score, and grade. For some reason there is a problem with the method that computes the average score. I have tried adding parenthesis and that didn't change the result either. This ultimately messes up the grade because the grade is calculated with the average score. Any help is appreciated, thanks! Here is my code:
import java.util.Scanner;
public class Student {
private String fname;
private String lname;
private int id;
private int score1;
private int score2;
private int score3;
private double average;
private String grade;
public void readInfo()
{
Scanner k = null;
k = new Scanner (System.in);
System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
fname = k.next();
System.out.println("Please enter the last name: ");
lname = k.next();
if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
System.exit(0);
System.out.println("Please enter the student ID: ");
id = k.nextInt();
System.out.println("Please enter the first score: ");
score1 = k.nextInt();
System.out.println("Please enter the second score: ");
score2 = k.nextInt();
System.out.println("Please enter the third score: ");
score3 = k.nextInt();
}
//The problem lies in here:
private void computeAverage()
{
average = score1+score2+score3/3.0;
}
private void computeGrade()
{
if (average>=90&&average<=100)
grade = "A";
else if (average>=80&&average<=89.9)
grade = "B";
else if (average>=70&&average<=79.9)
grade = "C";
else if (average>=60&&average<=69.9)
grade = "D";
else
grade = "F";
}
private String getName()
{
return fname + " " + lname;
}
private double getAverage()
{
return average;
}
public void printAll()
{
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
}
}
I guess the problem is because, you are not initializing the variable average anywhere.
Though, you have a method computeAverage(). Its not been called from anywhere in the program. Probably, you might also do it anywhere outside.
And please include parenthesis which will definitely produce the correct result.
Order of operations. What you are doing is sum 1 + sum 2 plus the quotient of sum3 and 3. When you divide, you must divide by exactly what you need to be divided. You should be doing (sum 1+ sum 2+ sum 3)/3
If you don't want to divide by 2, you can also multiply by one half, that won't change anything, but it's just another option.
(sum 1+ sum 2+ sum 3)*1/2
Keep in mind what you want to divide. If it is more term, take advantage of grouping symbols!
{Rich}
Related
So what I trying to do is ask users to put their weight and score of exam 1 & 2 and if they input the score, use those variables to figure out current score.
However, since scores are declared by users through scanner inside of if statement, it does not let me use those variables from outside of if statement.
How can I use variable 'examOneScore' and 'examTwoScore' when I want to calculate csEx1 and csEx2.
When I try to use those it says "The local variable examOneScore may not have been initialized."
import java.util.Scanner;
public class CurrentScore
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of secondexam? ");
String examTwo = keyboard.nextLine();
if(answerTwo.equalsIgnoreCase("yes") || answerTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
}
You have to define the variables that you want to use later outside of the if statement:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
double examOneScore = 1;
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of second exam? ");
String examTwo = keyboard.nextLine();
double examTwoScore = 1;
if(examTwo.equalsIgnoreCase("yes") || examTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
I used the value 1 for defining them, you have to look for yourself want you want to use there
I am working on a code where you have a students name and his grades and it prints his name total scores and his average scores. I want to make it more functional in allowing the user to input there name and scores and get all that info back. I may try to further this into a class average where it allows to input multiple individual names, scores, and average, print each one separately then showing the class average. This is a second thought though, as I need to have user input of grades and names first.
This is what I have so far.
I have a separate class to make some things simpler.
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then i have the main method:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
This is what it prints out currently:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
UPDATE:
This is what i have done so far. i added a loop and trying to use my student class but it doesn't seem to work with the array.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
Since you are only learning the language just yet, I'll give you a few suggestions to send you on your way. You might want to use a while-loop to consistently ask the user for a new grade until they've given you an empty line or something. You can reuse your scanner to read the new grades and they can be converted to integers using Integer.parseInt. Hopefully this'll allow you to write your code further, it's already looking great :).
EDIT
There are several points which can be improved upon in your edited code. The following shows some of them (using import java.io.Console;):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
I'm suppose to write a class with the following.
First Name
Last Name
ID
Score1
Score2
Score3
Average
Grade (for A, A-, B+, ...E).
All the data members are suppose to be private.
Below this is what I have and I named the class, Student.
import java.util.Scanner;
public class Student {
private String fname;
private String lname;
private int id;
private int score1;
private int score2;
private int score3;
private double average;
private String grade;
public void readInfo()
{
Scanner k = null;
k = new Scanner (System.in);
System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
fname = k.next();
System.out.println("Please enter the last name: ");
lname = k.next();
if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
System.exit(0);
System.out.println("Please enter the student ID: ");
id = k.nextInt();
System.out.println("Please enter the first score: ");
score1 = k.nextInt();
System.out.println("Please enter the second score: ");
score2 = k.nextInt();
System.out.println("Please enter the third score: ");
score3 = k.nextInt();
}
private void computeAverage()
{
average = (score1+score2+score3)/3;
}
private void computeGrade()
{
if (average>=90&&average<=100)
grade = "A";
else if (average>=80&&average<=89.9)
grade = "B";
else if (average>=70&&average<=79.9)
grade = "C";
else if (average>=60&&average<=69.9)
grade = "D";
else
grade = "F";
}
private String getName()
{
return fname + " " + lname;
}
private double getAverage()
{
return average;
}
public void printAll()
{
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
The problem I'm having is how to actually get the information to display on the console. I went ahead and created an instance and called it Averages of the Student class (the class thats listed above.)
Here is what I have of the other class called 'Averages'. I'm lost on what to do. First time actually in Java, only been studying it for two weeks. My book does not clarify anything. So? I assume I'm still learning the ropes and feeling annoyed, I cannot figure this probably (easy) part out. Thanks.
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
Scanner k= new Scanner(System.in);
Student[] students = new Student[36];
Student st, st2;
st = new Student();
st2 = new Student();
System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
System.out.println();
System.out.println("-----------------------------------------------------");
//System.out.printf("%-9s%-9s %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
System.out.println();
System.out.println("-----------------------------------------------------");
Here is a piece of code to help you.
It mainly populates the array with students' data, and computes and prints the class average :
public static void main(String[] args) {
int classSize = 36;
double cumulatedAverages = 0d;
Student[] students = new Student[classSize];
for(int i =0;i<students.length;i++){
Student student = new Student();
// populate student's data
student.readInfo();
// make calculations
student.computeGrade();
student.computeAverage();
cumulatedAverages = cumulatedAverages + student.getAverage();
// add the student to the array
students[i] = student;
}
// compute the class average
double classAverage = cumulatedAverages / classSize;
System.out.printf("%s %-3.2f","Class average is",classAverage);
}
I am new to stackoverflow. First I would like the program to loop with a price, then a question(enter another price?), price, then a question and so on. Below is the output.
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Please enter a price:
99
Please enter a price:
22
However it will keep looping at the end with "Please enter a price:". I want it to do:
Please enter a price:
33
Enter another price?
y
Please enter a price:
66
Enter another price?
y
Please enter a price:
22
Can anyone help me with this? Also, sometimes the average does not update fully. Thanks :)
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice;
System.out.println("Please enter a price: ");
integer = input.nextInt();
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
}
while (addPrice.equalsIgnoreCase("Y"));
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
You need to replace your while with an if
if (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
count = count + 1;
sum = sum + integer;
System.out.println("Please enter a price: ");
integer = input.nextInt();
}
In fact, addPrice is not modified within your second while loop, and so you have an infinite loop.
In order to do the averaged price, you're in the right way but not in the right place :P
count = count +1 and sum = sum + integer should be done after each integer = input.nextInt(). In your current code, you don't increment the counter and don't add the integer for the last input.
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
do {
System.out.println("Enter another price? ");
addPrice = input.next();
while (addPrice.equalsIgnoreCase("Y")) { // change this line to while user response = no etc may need a enter another number?
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++ ; // count = count +1
sum += integer ; // sum = sum + integer
}
}
while (addPrice.equalsIgnoreCase("Y"));
Finally here is a improved version which avoid the use of if.
int sum = 0;
int integer = 0;
String addPrice = "Y";
while( "Y".equalsIgnoreCase(addPrice) ) {
System.out.println("Please enter a price: ");
integer = input.next();
sum += integer ;
count++;
System.out.println("Enter another price? ");
addPrice = input.next();
}
int avg = sum / count ;
What you should do is change your logic a bit. You need to repeat two actions, entering a price and asking if the user wants to enter another price. Only one loop is required for this.
do {
System.out.println("Please enter a price: ");
integer = input.nextInt();
count = count + 1;
sum = sum + integer;
System.out.println("Enter another price? ");
addPrice = input.next();
} while (addPrice.equalsIgnoreCase("Y"));
i think you want something like this:
import java.util.Scanner;
public class ReadInPrice {
public static void main(String[] args) {
int integer = 0;
int count = 0;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
String addPrice = "Y";
while (addPrice.equalsIgnoreCase("Y")){
System.out.println("Please enter a price: ");
integer = input.nextInt();
count++;
sum += integer;
System.out.println("Enter another price? ");
addPrice = input.next();
}
average = sum / count;
System.out.println("Average = " + average);
input.close();
}
}
Try this:
EDIT Added min and max.
public class ReadInPrice {
public static void main(String[] args) {
//better to use 2 scanners when dealing with both string and int
//one for string ; one for ints
Scanner strScanner = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
boolean enter = true;
int sum = 0;
int count = 0;
int min=Integer.MAX_VALUE;
int max=0;
while (enter) { //while user wants to keep adding numbers
System.out.println("Please enter a price: ");
int price = intScanner.nextInt();
if(price < min)
min=price;
if(price > max)
max=price;
sum += price;
count++;
System.out.println("Enter another price? ");
String answer = strScanner.nextLine();
if (!answer.equalsIgnoreCase("Y"))
enter = false; //user doesn't want to keep adding numbers - exit while loop
}
double average = (double)sum / count;
System.out.println("Average = " + average);
System.out.println("Min = " + min);
System.out.println("Max = " + max);
strScanner.close();
intScanner.close();
System.exit(0);
}
}
I am working on a student scores application that accepts the last name, first name and score for one or more students and stores the results in an array. Then it prints the students and their scores in alphabetical order by last name. We do not know how many students there are, but there will be fewer than 100.
We have to display the class average at the end of the student information and display a message after each student whose grade is more than 10 points below the class average.
My first issue is that I have created a do/while loop to ask if the user would like to enter another but it will not work!?!?
Second, I can not figure out how to display the "10 points below" message on individual students.
public class Student implements Comparable
{
String firstName;
String lastName;
int score;
//stores last name, first name and score for each student
public Student(String lastName,String firstName,int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.score = score;
}
//implement the comparable interface so students can be sorted by name
public int compareTo(Object o)
{
Student otherStudent = (Student)o;
if(otherStudent.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(otherStudent.firstName);
}
else
{
return lastName.compareToIgnoreCase(otherStudent.lastName);
}
}
public String toString()
{
return lastName + ", " + firstName + ": " + score;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class StudentApp
{
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
Student [] studentArray;
String lastName;
String firstName;
int score = 0;
double average = 0;
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
do{
//code that uses variable to specify the array length
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
studentArray[i] = new Student(lastName, firstName, score);
double sum = 0.0;
sum += score;
average = sum/nStudent;
}
}while (getAnotherStudent());
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (score<= (average-10))
{
System.out.println ("Score 10 points under average");
}
}
System.out.println("Student Average:" +average);
}
public static boolean getAnotherStudent()
{
System.out.print("Another student? (y/n): " );
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
}
}
There are a few problems here:
Every time through the do...while, you reinstantiate studentArray and sum. This means that all of your previously iterated over data is nuked when getAnotherStudent() is true - you want to instantiate the array and sum only once.
You don't stop if you have more than 100 students. You need an ending condition around nStudent as well in your loop.
You should make a few adjustments to getAnotherStudent() so that you can block on data, and wait when valid data is input - by using a loop:
public static boolean getAnotherStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) {
String choice = sc.next();
// blocks here - ignores all input that isn't "y" or "n"
while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
if (choice.equalsIgnoreCase("Y")) {
return true;
}
System.out.print("Another student? (y/n): " );
choice = sc.next();
}
}
return false; // obligatory
Your code is close there are just a couple of problems. The reason why your do while loop is not working is that you have a for loop inside of it. This means that you will ask for 100 students before you ask if they want to add another one. Your sum is being created inside this loop so it will be reset each time.
Finally you do not know how many Students will be added but your code assumes there will be 100 Students. This means you cannot use the for each loop to go through the array as some could be null. Just use a regular for loop going up to the last index of a student you added. Here are the changes:
Student[] student = new Student[nStudent];
int studentCount = 0; //declear the counter outside the loop
double sum = 0.0; //declear the sum outside the loop
do {
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
student[studentCount] = new Student(lastName, firstName, score);
sum += score; //increase the sum
studentCount++; //increment the counter
} while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
average = sum / studentCount; //work out the average outside the loop
System.out.println();
for (int i= 0; i< studentCount; i++ ) {
System.out.println(aStudent);
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
}
}
System.out.println("Student Average:" + average);
}
Your getAnotherStudent() method should read:
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) { // blocks until user entered something
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
} else {
// won't come here
return false;
}