Write a program to calculate the current grade based on the CSE 1341 syllabus. The program should prompt the user for their first and last name. It will then pass those names as Strings to the second method of the CSE1341Grade class. The name of the second method will be calcGrade. This method will prompt the user for the count of exam scores, count of quiz scores, and count of lab scores to entered by the user.
It will then utilize repetition structure to prompt for exam grades, quiz grades and lab grades based on the previous counts entered. For example, if the user entered count of exam scores to be 2; then the program will loop 2 times to input the two exam grades; and similarly for the count of quiz and count lab grades.
Assume you have a 100% attendance record and you will get all 5% of the attendance grade.
Use the syllabus to determine the weights of each of the categories such as the exams, quizzes and labs. Add 5% to the total score since you had perfect attendance.
Assume: all exams, labs and quiz scores are out of 100 points.
Sample Run:

java CSE1341Grade
First name: James
Last name: Bond
How many exam grades do you have? 1
How many quiz grades do you have? 2
How many lab grades do you have? 2
Enter exam 1 score: 90
Enter quiz 1 score: 80
Enter quiz 2 score: 80
Enter lab 1 score: 90
Enter lab 2 score: 90
Total Score: 84.55
James Bond your grade is a: B
^^That is my homework assignment, and this is what I have done so far
import java.util.Scanner;
public class CSE1341Grade
{
public static void main(String [] args)
{
//set up Scanner for user input, prompt for first name, define variable, and print response
Scanner s = new Scanner(System.in);
System.out.print("First name: ");
String first = s.nextLine();
System.out.printf(" %s\n", first);
//prompt user for last name, define variable, and print response
System.out.print("Last name: ");
String last = s.nextLine();
System.out.printf(" %s\n", last);
}
public static void calcGrade(String first, String last)
{
//prompt user for number of exam grades, define exam variable, print response
System.out.print("How many exam grades do you have? ");
String exam = s.nextLine();
System.out.printf(" %s\n", exam);
//prompt user for number of quiz grades, define quiz variable, print response
System.out.print("How many quiz grades do you have? ");
String quiz = s.nextLine();
System.out.printf(" %s\n", quiz);
//prompt user for number of lab grades, define lab variable, print response
System.out.print("How many lab grades do you have? ");
String lab = s.nextLine();
System.out.printf(" %s\n", lab);
while (exam != -1)
{
System.out.print("Enter " exam 1 " score: ", ++exam)
//define variables for computations
int score = 0;
int grade = 0;
//if statement to determine the final letter grade
if(score >= 90 && score <=100){
grade = 'A'; }
else if(score >=80 && score < 90){
grade = 'B'; }
else if(score >= 70 && score < 80){
grade = 'C'; }
else if(score >=60 && score < 70){
grade = 'D'; }
else {
grade = 'F'; }
}
}
My problem is figuring out how to create a loop that will prompt the user for however many exam grades needed.
I have performed few changes to your code based in the comments ..
Here you can see the diff
http://www.mergely.com/LIckVifT/
Note: It still does not finish your homework :-)
Update: Since the index in the foor loop does not really matters you could use it as this:
for (int i = 1; i <= examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + i + " score: ");
instead of
for (int i = 0; i < examsCount; i++) {
// using i+1 to print starting from 1 instead of 0
System.out.print("Enter " + (i + 1) + " score: ");
I like to do a loop and continue to ask the user for input until I get the result I want:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
while(shouldContinue) {
// do program logic
System.out.print("Should we continue? [Y or N] >> ");
if (input.nextLine().equalsIgnoreCase("N")) {
shouldContinue = false;
}
}
}
This is a relatively "structured" way to do an interaction loop and continue running a program over and over so long as the user wants.
-- UPDATE --
To do a number of iterations that you know ahead of time, simply pipe that into your counter for the loop:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of grades to enter [number] : ");
int numberOfTimesToIterate = input.nextInt();
for (int i = 0; i < numberOfTimesToIterate; i++) {
// do stuff here
}
}
Pseudo-code:
function(int n) {
for (i = n, i > 0, i--) {
\\prompt user
}
}
That should give you the general idea of how to do it, namely taking the amount, and subtracting 1 from it until you reach 0, each time getting the data and doing what it needs to do with it. Don't forget to make sure that n never equals less than zero (invalid), and that n is an integer. Otherwise, it is desirable that you have the function simply prompt the user for an amount, then pass that amount to the function that actually uses it. Alternatively, create a function which iterates n times and calls a function passed to it as an argument that many times (much harder to correctly do).
Something like this should work for you.
System.out.println("Please enter the number of exam grades you want to enter");
int grade_count = s.nextInt();
int [] grades = new int[grade_count];
for(int i =0; i<grade_count; i++){
System.out.println("Enter grade for "+i+1 +"Exam");
grades[i] = s.nextInt();
}
Related
import java.util.Scanner;
public class AverageMark{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int mark[] = { 0, 0, 0, 0 };
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
}
System.out.println("Thanks for entering your marks.\n");
double average = (mark[0] + mark[1] + mark[2] + mark[3]) * 0.25;
String grade;
if (average >= 90) {
grade = "A+";
} else if (average >= 80) {
grade = "A";
} else if (average >= 70) {
grade = "B";
} else if (average >= 60) {
grade = "C";
} else if (average >= 50) {
grade = "D";
} else
grade = "F";
System.out.printf("Your average is: %.2f\n", average);
System.out.printf("Your average of %.2f has a letter grade of %s", average, grade);
}
}
//Hi sorry about the prior edit, I am new to this site. This is the code I wrote but I'm not sure why it won't run. It seems something might be missing but I'm
quite unclear. Please help thank you
Your code is almost there, just missing to store the values entered by user :
Store the marks in the array :
System.out.println("Enter the marks : ");
for (int i =0; i < mark.length; i ++) {
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
// assign each input to an index of the array
mark[i] = input.nextInt();
}
I would also advice you to declare the array like below rather than just initialing all the indexes to 0
int mark[] = new int[4];
The rest of your code works as it is.
There are some issues with the code.
The first error you see is:
AverageMark.java:13: error: <identifier> expected
System.out.println("Thanks for entering your marks.\n");
This is because you have a closing curly brace where it is not needed. The Java compiler is having difficulty interpreting the structure of your program. Remove line 11. You need to have matching curly braces to form a syntactically correct program. Did you mean to include a for loop ?
Once you correct that and recompile you'll find that:
AverageMark.java:10: error: cannot find symbol
System.out.printf("Enter integer mark %s between 0 and 100: ", i + 1);
symbol: variable i location: class AverageMark 1 error
Add the definition for int i=0 before the reference to i on line 10.
It should then compile and you can start debugging.
In below program , I am giving flexibility to user to enter number of subjects. Scanner allows the user to read values of various types. System.in: An InputStream which is typically connected to keyboard input of console program.
import java.util.Scanner;
class AverageMarks
{
public static void main(String args[])
{
int i;
System.out.println("Enter number of subjects");
Scanner sc=new Scanner(System.in);
//Here we are taking number of subjects from user
int n=sc.nextInt();
//Set array to no of subject
int[] a=new int[n];
double avg=0;
System.out.println("Enter marks");
// Taking marks from user for n no of subjects
for( i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
// Calculating total marks of subjects in avg variable
for( i=0;i<n;i++)
{
avg=avg+a[i];
System.out.println("Total marks of subjects : => "+avg);
}
//Calculating average % using total/no of subject formula
for(i=0;i<n-1;i++)
{
System.out.print(a[i]+",");
}
System.out.println(a[i]+") ="+avg/n);
}
}
I'm attempting to write a method that allows the user to input the number of players on a sports team, the number of games played, the names of the players, and the amount of points scored per player per game.
Basically, I want the following display output where all information has been provided by the user:
Player Game 1 Game 2 Game 3 Game 4
Tom
Dick
Harry
Matthew
John
... and then points scored by each player in each game.
I admit that this little project originated from a homework assignment, but I've already turned the assignment in and the assignment didn't even ask for user supplied input. I really just want to know how to do this.
Below is my code. A few problems.
I assign each player's name to an array called playerRoster. Don't all array initialize at arrayName[0]? But when I print out playerRoster[0], nothing displays. When I print out playerRoster[1], the first name I enter for the array (which should be indexed at playerRoster[0]) displays. Why?
Related to above: I am prompted to enter the number of players on roster, and say I enter the number 5. But the prompt then allows me to only enter 4 names. Why?
The display above is what I'm looking for, and I'm sure there are built in Java methods for displaying a table of values. I actually don't want that. I kind of want to go forward with loops, like I'm doing now. (I know, I know - beggars can't be choosers)
Here is my code
import java.util.*;
public class BasketballScores
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println ("Enter the number of players on roster: ");
int numPlayers = input.nextInt();
System.out.println();
System.out.println ("Enter the number of games played: ");
int numGames = input.nextInt();
System.out.println();
int[][] arrayScores = new int[numPlayers][numGames];
String[] playerRoster = new String[numPlayers];
System.out.println ("Enter player names: ");
for (int j = 0; j < numPlayers; j++)
{
playerRoster[j] = input.nextLine();
}
for (String element: playerRoster)
{
System.out.println (element);
}
System.out.println();
System.out.println ("Enter the points scored per player per game: ");
System.out.println();
System.out.print (playerRoster[1]);
for (int i = 0; i < numPlayers; i++)
{
for (int k = 0; k < numGames; k++)
{
arrayScores[i][k] = input.nextInt();
}
}
System.out.println();
for (int i = 0; i < numPlayers; i++)
{
System.out.println();
for (int k = 0; k < numGames; k++)
{
System.out.print (arrayScores[i][k] + ", ");
}
}
}
}
First, before you get your player names, you are still on the line with the numGames. You need to call input.nextLine() before attempting to parse your names. This should solve your first 2 questions. What happens with #nextLine is you are going to the end of the line of the current line you are on. After you get your numGames you are still on that line. Call input.nextLine() to advance to the lines with your player names.
System.out.println ("Enter the number of players on roster: ");
int numPlayers = input.nextInt();
System.out.println();
System.out.println ("Enter the number of games played: ");
int numGames = input.nextInt();
input.nextLine(); //You need this to go to the next line before attempting to get your player names.
System.out.println();
int[][] arrayScores = new int[numPlayers][numGames];
String[] playerRoster = new String[numPlayers];
System.out.println ("Enter player names: ");
for (int j = 0; j < numPlayers; j++)
{
playerRoster[j] = input.nextLine();
}
For formatting your print you can use System.out.printf. Here is a quick example for your situation that you should be able to utilize. Quick reference guide
String[] players = new String[]{"Tom", "Dick", "Harry", "Matthew", "Johh"};
System.out.printf("%-10s%6s%6s%6s%6s","Player", "Game1 ", "Game2 ", "Game3 ", "Game4 ");
System.out.println();
Random r = new Random();
for (String player : players){
System.out.printf("%-10s%3d%6d%6d%6d",player, r.nextInt(10), r.nextInt(10), r.nextInt(10), r.nextInt(10));
System.out.println();
}
Output:
Player Game1 Game2 Game3 Game4
Tom 2 9 7 3
Dick 8 1 8 4
Harry 9 2 0 2
Matthew 5 1 3 2
Johh 8 4 0 2
Once you share how you are trying to input your data, I can help a little more. Hope this helps!
im trying to write a program that will accept input of "put name mark", "get name mark" and "quit"
upon the user entering "put name mark" the program will prompt them to enter a student name and mark and then stores it at the next available array index.
the "get name" command will accept a name input from the user and they iterate through the array and display any mark matching the name entered.
the "quit" command will end the program and return the mean mark and the highest mark in the display.
the problem im having is that it dosent seem to be entering the loop when i type the required words in. it just jumps to where it asks the question again and wont even accept input
im still a beginner and ive been working on this program for 4 weeks so any help would be greatly appreciated.
package week14;
import java.util.Scanner;
public class week {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//sets number of string inputs
{
String[] names = new String[50];
double[] scores = new double[50];
// Enter student name and score
System.out.print("please enter either: quit, put name mark, get name");
input.next();
if(input.next() == "put name mark" )
{
System.out.print("Enter Student Name");
names[50] = input.next();
System.out.print("Enter Score");
scores[50] = input.nextInt();
}
System.out.println("please enter either: quit, quit, put name mark, get name");
input.next();
if(input.next() == "get name")
{
System.out.print("please enter the name you would like to display the score for");
String get = input.next();
}
// Sort
for (int i = 50 - 1; i >= 1; i--) {
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++) {
if (currentMax < scores[j]) {
currentMax = scores[j];
currentMaxIndex = j;
}
}
// Swap scores[i] with scores[currentMaxIndex];
// Swap names[i] with names[currentMaxIndex] ;
if (currentMaxIndex != i) {
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
if (input.equals("quit")){
System.out.print(names[i] + scores[i]);
System.out.println();
System.out.print(currentMax);
break;
}
}
}
}
}
That's what i got for now maybe there are some errors if there is any problem say what's it and I'll fix it.
import java.util.Scanner;
public class Week
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Scanner used to get input from the user
String[] names = new String[50]; //The array for names remember arrays index began with 0 not 1
int[] scores = new int[50]; //Again arrays began with 0 not 1 and the last is n-1
int last = 0; //Used to store the last added ID
String command; //The command from the user
boolean running = true; //Whenever the program is running or not
while(running)
{
System.out.println("please enter either: quit, put name mark, get name"); //Print the command list
command = input.nextLine(); //The next input line (This will make the Thread pause untill it get and input)
if(command.equals("put mark")) //If the command is "put mark"
{
if(last == 49) //Check because we can create and Exception by adding too much element to and array
System.out.println("Max number of people reached"); //So we can't add more people
else
{
System.out.println("Enter Student Name"); //Print the questin
names[last] = input.nextLine(); //The name
System.out.println("Enter Score"); //Ask for the score
scores[last] = input.nextInt(); //Get the score ,because score is a double we should use double so it can take numbers like 0.1
last++; //Increment last with 1
}
}else if(command.equals("get name"))
{
System.out.println("please enter the name you would like to display the score for");
String name = input.nextLine(); //Get the name
for(int i = 0; i < last; i++) //Loop untill we hit the last added name's ID
if(names[i].equals(name)) //Check if the names[i] is the name that we're searching for
System.out.println(name + " 's score is " + scores[i]); //If it's then we print it out
}else if(command.equals("quit"))
{
running = false; //The loop will never run again
//Implement sorting for youself I would use Map<K, V> but you didn't learned it so..
//In this case you have to make 1 loop to sort both of the arrays by sorting the second array
//and when you move anything must it in both arrays I can't help you to make this sorry
for(int i = 0; i < last; i++) //We print the sorted arrays of the people and their scores
System.out.println(names[i] + " 's score is " + scores[i]); //Let's print it
}
}
}
}
My program should ask the user to enter some grades. After the input is finished, the program has to show which grade was entered how many times (or in another word, how many times each grade was entered).
For example, if the user enters grade 3 two times, thats menas total 2 students has got the grade 3. If the grade F is entered 3 times, that means 3 students has got the failing grade F, and so on....
The final output should look something like this:
Example output:
grade F= 3 students
grade 3= 2 studnets
and so on....
...........................
...........................
Now my problem is with keeping track of each grade and print them out telling how many times (also means how many students got each specific grade) each of the grade was entered. I can't come up with idea to solve it.
My code:
package studentgrade;
import java.util.*;
public class StudentGrade {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many total grade you want to enter (Depending on the total number of students)? ");
int totalStudents = input.nextInt();
String grade[] = new String[totalStudents];
//asking user to enter grade
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter grade " + (i + 1) + ": ");
System.out.println("Choose only between grade 3 and F:\n");
grade[i] = input.next();
if (grade[i] == "3") {//3 defines the only passing grade
//Store that into a variable
} else if (grade[i].equalsIgnoreCase("F")) {//F defines the failing grade
//Store that into a variable
}//else{
//System.out.println("Invalid input. Try again");
//}
}
//Now print out which grade was entered how many times
}
}
Define, at the top, a variable resembling each grade and set them to 0, and then, each time in the "if" statement, add one to the corresponding variable. variable++.
At the end, use
System.out.println("Grade 3: " + variable3);
System.out.println("Grade F: " + variableF);
Also, use .equals method to compare two strings in the if statement
If you don't need the sort of introduced values, simply create an array with your needed size n (don't see exactly what means from 3 to F).
int[] grade = new int[n];
If all inputs where numbers you can make direct:
grade[input.next()] ++;
Then, as all inputs are not int you can solve it with a switch
switch(input.next()) {
case "3":
grade[0] ++;
case "2":
grade[1] ++;
....
case "F":
grade[n-1] ++;
}
This is a good use for a Map. Right now your only storing the inputs 3 and F but if you wanted to adapt this program to have more grades this would scale perfectly and it is a clean and neat solution.
// the map to store how many times a grade was entered
private static final Map<String, Integer> gradeSumMap = new HashMap<String, Integer>();
public static void addToGradeSum(String key, int num) {
if(gradeSumMap.get(key) == null) {
gradeSumMap.put(key, num);
} else {
gradeSumMap.put(key, gradeSumMap.get(key) + num);
}
}
public static void printGradeSumMap() {
for(String key : gradeSumMap.keySet()) {
System.out.println("grade " + key + " = " + gradeSumMap.get(key));
}
}
// this needs to also be .equals or .equalsIgnoreCase
if (grade[i].equals("3")) {
addToGradeSum(grade[i], 1);
} else if (grade[i].equalsIgnoreCase("F")) {
addToGradeSum(grade[i], 1);
}
then just call printGradeSumMap() when you want to print it
I'm having a few problems with my code, this is the over all goal of the program.
One of your professors hears of your emerging programming expertise and asks you to write a SINGLE program that can be used to help them with their grading. The professor gives three 50-point exams and a single 100-point final exam. Your program will prompt the user for the student’s name, entered as Firstname Lastname (i.e. Bob Smith), the student’s 3-exam scores and 1-final exam score (all whole numbers). Class size varies from semester to semester, but 100 is the limit (declare as a constant).
Read in information for ALL students before doing any calculations or displaying any output. Verify that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered. Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid, display an error message and allow the user to re-enter that invalid score. Once all student info is read in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade.
This is what I have:
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
final int MAX_STUDENTS = 100;
final int MIN_EXAM = 0;
final int MAX_EXAM = 50;
final int MIN_FINAL = 0;
final int MAX_FINAL = 100;
String[] names = new String[MAX_STUDENTS];
int [] exams = new int[MAX_STUDENTS * 4];
int student = 1;
do
{
System.out.print("PLease enter the name of student " + student + ": " );
for (int k = 0; k < 1; k++) {
names[k] = s.nextLine().toUpperCase();
}
for ( int i = 0; i < 4; i++){
if(i==3){
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
}
else{
System.out.print("Please enter score for Exam " + (i+1) + ": ");
exams[i] = s.nextInt();
if((exams[0]<MIN_EXAM||exams[0]>MAX_EXAM)||(exams[1]<MIN_EXAM||exams[1]>MAX_EXAM)||(exams[2]<MIN_EXAM||exams[2]>MAX_EXAM)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[3]<MIN_FINAL||exams[3]>MAX_FINAL){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if(again!="y")
student++;
}while (again.equalsIgnoreCase ("y"));
System.out.println("***Class Results***");
System.out.println(names[1] + "," + names[0] + " " + "Exam Percentage: "+ ((exams[0]+exams[1]+exams[2]+exams[3])/(MAX_EXAM*3+MAX_FINAL)));
}
}
The problems i have have are:
figuring out how to assign the user entered test scores beyond just the first student, i believe i have it set up correct for just one, but it runs into a problem when i would move on to the second student.
For some reason that I cannot figure out the line
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
doesn't allow me to enter anything, not y not n not anything, so my program effectively ends there, it doesn't make sense to me because I've done it exactly like that before and it has worked.
other than that, if there are any other problems that you can see with my code pointing them out would be extremely helpful.
Thank you
EDIT-
new problem i am having, after changing to
if(!again.equalsIgnoreCase("y"))
student++;
}while (again.equalsIgnoreCase ("y"));
it lets me type things in now, but after i type in y it prints the next line as
Please enter the name of student 1: Please enter score for Exam 1:
I don't know why or what i need to change to fix it, any suggestions?
`if(again!="y")` is the culprit here
You should use equals() method to check string equality.
if(!again.equals("y"))
If you compare Strings in Java using the == or != operators then you are not actually comparing the values. Instead you are testing if the two Strings are the same Object.
This post explains String comparison well.
To do what you want, change if (again != "y") to if(! (again.equalsIgnoreCase("y")) )
EDIT
I believe your new problem stems from the first for loop you do inside your do loop. Each time you type "y" at the end of your do/while you are going to execute the entire
for (int k = 0; k < 1; k++) {
loop again. This is why after you type "y" you are seeing Please enter the name of student 1: Please enter score for Exam 1:
A "solution" to your new issue would be to make it so the outer for enclosed the inner one, looping through 4 exams for each student usually referred to as a "double for" or "nested for loop".
That said you would then be presented with the issue of having all the exams for ALL students in a single array.
I think now is the time to sit down and put some serious thought into the design of your program. It would be much easier for you if you used a Student object to represent a student and hold their exam scores, IMO. Then you could create an array of Students as opposed to two different arrays you have now.
Here are some "starter" steps (Not necessarily a complete list):
Make a Student class that has variables for the student's first & last name, as well as an array to hold that Students exam scores
In your main class create an ArrayList to hold all of the new Student objects you will be creating.
Do your do/while loop. At the beginning of the loop create a new Student object. Then ask for the Students name and exam scores (note that if you KNOW there will only be the 4 exam scores you don't have to do any extra logic there. You can simply ask for the 4 exam scores using a for loop, or if you want all at one time. if there are a variable number of scores you will have to do some sort of check)
Add the new Student you have created to the ArrayList of Students.
Once the person selects "n", loop through the ArrayList and print the information for each Student!
Your for (int k = 0; k < 1; k++) loop will execute only once (for one student) because you have it set up to execute only while k < 1, which will happen only once. As soon, as you increase k to 1, the loop will stop. I would change it to for (int k = 0; k < MAX_STUDENTS; k++) to make sure it will loop through until you reach the max number of students allowed.