So I am trying to create a list without creating an array list, however, whenever I try to run the program I get the error "The local variable "letterGrade" may not have been initialized" I have tried changing the whole code but I still have the same problem >.< any help will be greatly appreciated. Thank you in advance.
import java.util.Scanner;
public class KifahProg4
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String lastName,firstName,fullName,list;
int score,countA,countB,countC,countD,countF; //Student scores and number of Grades
int total = 0; //Student total score
double average; //Student Average score
char letterGrade; //Student grade
char response; //User continue y/n
do
{
System.out.print("Enter the student last name: ");
lastName = stdIn.next();
System.out.print("Enter the student first name: ");
firstName = stdIn.next();
fullName = lastName + " " + firstName;
for (int i=0; i<=5; i++)
{
System.out.print("Enter the score: ");
score = stdIn.nextInt();
total += score;
average = (double) total/5;
if(average >= 90 && average <=100)
{
letterGrade = 'A';
}
else if (average >=80)
{
letterGrade = 'B';
}
else if (average >=70)
{
letterGrade = 'C';
}
else if (average >= 60)
{
letterGrade = 'D';
}
else if (average <= 59)
{
letterGrade = 'F';
}
System.out.println("Grade is: " );
list = fullName + "\t" + total + average + "\t" + letterGrade + "\n";
}
System.out.println(
"Would you like to add another student? (y/n): ");
response = stdIn.next().charAt(0);
} while (response == 'y' || response == 'Y');
} // end main
} // end class KifahProg4
Set letterGrade to some default value before you use it to get rid of the compiler warning you're getting.
e.g.
char letterGrade = 'Z';
If it is still set to 'Z' when you get to list = fullName + "\t" + total + average + "\t" + letterGrade + "\n"; you know you have an error condition...
Related
I made the invalid grades into " " but it seems in output it's showing space like this https://i.stack.imgur.com/3kHZW.png how to show only the valid grades? the invalid grades is making blank space in output
This is the question https://i.stack.imgur.com/uxLhG.png
This is the needed output https://i.stack.imgur.com/HNZpZ.png
This is my Program
String [][] student = new String[100][3];
int stu = 0, totalp=0, totalf=0;
for(int h=0; h<100; h++) {
System.out.print("Enter Name: ");
student[h][0] = sc.nextLine();
System.out.print("Enter Grade: ");
student[h][1] = sc.nextLine();
int grade = Integer.parseInt(student[h][1]);
if(grade >100 || grade <50) {
student[h][0] = "";
student[h][1] = "";
student[h][2] = "";
System.out.println("Invalid Grade");
}
else if(grade >=75) {
student[h][2] = ("Passed");
totalp++;
}
else if(grade <=74) {
student[h][2] = ("Failed");
totalf++;
}
System.out.print("Add new record (Y/N)?: ");
char choice = sc.nextLine().charAt(0);
System.out.println("");
if(choice == 'y' || choice =='Y') {
stu++;
continue;
}
else if(choice == 'n' ||choice =='N') {
break;
}
}
System.out.println("\nGRADE SUMMARY REPORT");
System.out.println("\nName\tGrades\tRemarks");
for(int i =0; i<stu+1; i++) {
for(int h =0; h<student[i].length; h++) {
System.out.print(student[i][h] + "\t");
}
System.out.println();
}
System.out.println("\nTotal Passed: " + totalp);
System.out.println("Total Failed: "+ totalf);
If a grade entered by the user is invalid, just don't add it to student array. Then it won't get printed at all. You should also handle the case where the user does not enter a number when asked to enter a grade.
When asking the user if she wants to add a new record, you only need to check whether she entered a Y. Anything else can be considered a no.
The below code uses method printf to format the report. Also, in order to format the report, I keep track of the longest name entered by the user.
import java.util.Scanner;
public class Students {
private static final int MAX_ROWS = 100;
private static final int NAME = 0;
private static final int GRADE = 1;
private static final int REMARK = 2;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String[][] student = new String[MAX_ROWS][3];
int totalp = 0, totalf = 0, longest = 0;
int h = 0;
while (h < MAX_ROWS) {
System.out.print("Enter Name: ");
String name = sc.nextLine();
int len = name.length();
if (len > longest) {
longest = len;
}
System.out.print("Enter Grade: ");
String grade = sc.nextLine();
try {
int mark = Integer.parseInt(grade);
if (mark >= 50 && mark <= 100) {
student[h][NAME] = name;
student[h][GRADE] = grade;
if (mark >= 75) {
student[h][REMARK] = "Passed";
totalp++;
}
else {
student[h][REMARK] = "Failed";
totalf++;
}
h++;
if (h == MAX_ROWS) {
System.out.println("Maximum students entered.");
}
else {
System.out.print("Add new record (Y/N)?: ");
String choice = sc.nextLine();
if (!"Y".equalsIgnoreCase(choice)) {
break;
}
}
}
else {
throw new NumberFormatException();
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Invalid. Grade is a number between 50 and 100.");
}
System.out.println();
}
System.out.println("\nGRADE SUMMARY REPORT\n");
if (longest < 4) {
longest = 4;;
}
System.out.printf("%-" + longest + "s", "Name");
System.out.println(" Grade Remarks");
String format = "%-" + longest + "s %4s %s%n";
for (int i = 0; i < h; i++) {
System.out.printf(format, student[i][NAME], student[i][GRADE], student[i][REMARK]);
}
System.out.println();
System.out.println("Total passed: " + totalp);
System.out.println("Total failed: " + totalf);
}
}
Here is output from a sample run of the above code:
Enter Name: Superman
Enter Grade: 99
Add new record (Y/N)?: y
Enter Name: Batman
Enter Grade: 23
Invalid. Grade is a number between 50 and 100.
Enter Name: Iron Man
Enter Grade: 74
Add new record (Y/N)?: n
GRADE SUMMARY REPORT
Name Grade Remarks
Superman 99 Passed
Iron Man 74 Failed
Total passed: 1
Total failed: 1
You may also want to refer to the Exceptions lesson in Oracle's Java tutorials.
right now you are still printing the invalid grades in a line. what you want is to check and make sure the grade is valid before printing it. Since you made all the invalid grade an empty string, you can simply check for that like so
if(!student[i][h].isEmpty()){
System.out.print(student[i][h] + "\t");
}
This program is about a user being prompted to enter how many tests they want the average of and then the program will ask them to input however many they said. I am having trouble identifying how the code does that. What makes it know to return as many inputs as the user asks. Thank you!
I looked at the while function but that seems to only be if the user inputs something like 0 or a negative number (I think).
import java.util.Scanner;
public class average {
public static String getLetterGrade(double average) {
if (average < 60) {
return "F";
} else if (average < 70) {
return "D";
} else if (average < 80) {
return "C";
} else if (average < 90){
return "B";
}
else;{
return "A";
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome, please type your first name. ");
String name = scan.nextLine();
System.out.println("Welcome, please type your last name. ");
String last = scan.nextLine();
int n;
System.out.println("How many tests would you like the average of?");
n = scan.nextInt();
while(n<0) {
System.out.println("Invalid input.");
System.out.println("How many tests would you like the average
of?");
n = scan.nextInt();
}
double sum = 0, grade;
System.out.println("Enter " + n + " scores.");
for(int i = 0;i<n;i++) {
grade = scan.nextDouble();
sum += grade;
}
double average = (sum/n);
System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", your
average score is " + (average));
System.out.println("Your letter grade is a " +
getLetterGrade(average));
}
}
There are no errors in this program it runs and does what it is suppose to do.
Can someone please tell me why my code is not providing the correct output? Here aare the instructions "
I need to write a program that reads student scores, gets the best
score, and then assigns grades based on the following scheme:
1) Grade is A if score is >= best - 10
2) Grade is B if score is >= best - 20;
3) Grade is C if score is >= best - 30;
4) Grade is D if score is >= best - 40;
5) Grade is F otherwise.
The program prompts the user to enter the total number of students, then prompts the user to enter all of the scores, and concludes by displaying the grades. My problem comes from pulling the grades from an array, this is what I have so far:
// Here is my code. Thank You
import java.util.Scanner; // imports the scanner function
public class NBpractice { //class is formed
public static void main(String []args) { // main method
// user input is asked for the number of students
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int studentNum = input.nextInt();
//user input is asked for students scores
Scanner input2 = new Scanner(System.in);
System.out.print("Enter " + studentNum + " scores: ");
int scores = input2.nextInt();
int best = 80;
char letterGrade;
int scoresArray[] = new int[studentNum]; // array is created and holds the # of place values as students
for (int i = 0; i < scoresArray.length; i++) { // for loop created
scoresArray[i] = input2.nextInt(); //array values are assigned to user's input
best = scoresArray[0];
if (best < scoresArray[i]) {
best = scoresArray[i];
}
//-----------------------------------------------------------------------------
if (scores >= (best - 10)) {
letterGrade = 'A';
}
else if (scores >= (best - 20)) {
letterGrade = 'B';
}
else if (scores
>= (best - 30)) {
letterGrade = 'C';
}
else if (scores >= (best - 30)) {
letterGrade = 'D';
}
else {
letterGrade = 'F';
}
System.out.println("Student " + i + " Score is " + scoresArray[i] + " and grade is: " + letterGrade );
}
//------------------------------------------------------------
}
}
Some pointers...
This: System.out.print("Enter " + studentNum + " scores: "); and int scores = input2.nextInt(); need to go in the for loop body.
Use the for loop to populate the array.
Once that the for loop is executed, find the best (highest) score in the array.
Use another for loop to sort out the grades.
As is, your program will only ask for the grades and pretty much assumes that the best grade is 80, which might not always be the case.
You'll need two separate for loops. One to read the grades, and get the best, and the second for loop to normalize the grades.
int[] scores = new int[amount];
int best = -1;
for(int i = 0; i < amount; i++)
{
scores[i] = in.nextInt();
if(scores[i] > best)
best = scores[i];
}
System.out.println(Arrays.toString(scores));
// Now that we have the best, we can normalize
// the rest of the scores based on the best
// and assign the corresponding letter grade.
String[] grades = new String[amount];
for(int i = 0; i < amount; i++)
{
int score = scores[i] * 100 / best;
if(score >= 90)
grades[i] = "A";
else if(score >= 80)
grades[i] = "B";
else if(score >= 70)
grades[i] = "C";
else if(score >= 60)
grades[i] = "D";
else
grades[i] = "F";
scores[i] = score;
}
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(grades));
Test input 80 60 75 83 67 outputs:
[80, 60, 75, 83, 67]
[96, 72, 90, 100, 80]
[A, C, A, A, B]
I would recommend using a Student class and not work with parallel lists or arrays. A Student class can for example look like this:
class Student {
int score;
String grade; // could also be an Enum
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score;
}
public String getGrade() {
return this.grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" + "score=" + score + ", grade='" + grade + '\'' + '}';
}
}
You can then make instance of the Students and add them to an ArrayList in you public static void main.
I think you have to use two loops because you cannot know beforehand what the best grade will be. In your main you can make enter the students add them to a List and compare their grades;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int highScore = 0;
int numOfStudent = input.nextInt();
List<Student> studentList = new ArrayList<>();
for (int i = 1; i <= numOfStudent; i++) { // you might want to add Exception handling here, by surrounding it with a try / catch or do more checks than only i <= numOfStudent
System.out.printf("please fill in the score of student no %d \n", i);
int score = input.nextInt();
Student student = new Student();
student.setScore(score);
if (score > highScore) {
highScore = score;
}
studentList.add(student);
}
System.out.println("these are the scores and grades of the Students");
for (Student s : studentList) {
if (s.getScore() >= highScore - 10) {
s.setGrade("A");
}
else if (s.getScore() >= highScore - 20) {
s.setGrade("B");
}
else if (s.getScore() >= highScore - 30) {
s.setGrade("C");
}
else if (s.getScore() >= highScore - 40) {
s.setGrade("D");
}
else {
s.setGrade("F");
}
System.out.println(s);
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_1 {
public static void main(String[] args) {
// Assign grades
Scanner input = new Scanner(System.in);
int numStudents;
int[] scores;
int best;
System.out.println("Enter the number of students: ");
numStudents = input.nextInt();
scores = new int[numStudents];
System.out.println("Enter " + numStudents + " scores: ");
for (int i = 0; i < numStudents; i++) {
scores[i] = input.nextInt();
}
displayGrades(findBestScore(scores), scores);
}
public static int findBestScore(int[] scores) {
int best = scores[0];
for (int i = 1; i < scores.length-1; i++) {
if (scores[i] > best)
best = scores[i];
}
return best;
}
public static void displayGrades(int best, int[] scores ) {
char grade = ' ';
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= best-10)
grade = 'A';
else if (best - 10 > scores[i] && scores[i] >= best - 20)
grade = 'B';
else if (best - 20 > scores[i] && scores[i] >= best -30)
grade = 'C';
else if (best - 30 > scores[i] && scores[i] >= best -40)
grade = 'D';
else if (best - 40 > scores[i])
grade = 'F';
System.out.println("Student " + i + " score is " + scores[i] + " and grade is " + grade);
}
}
}
I'm trying to make a grade calculator. Everything is working to specifications except the program is not handling the conditionals correctly to output the right letter grade.
Any help on this?
import java.util.Scanner;
public class GradeCalculator {
public static void main(String args []) {
String name;
String major;
int attendance;
int homework;
int project1;
int project2;
int midterm;
int finalexam;
int extra;
String finalgrade;
double attweight = 0.05;
double hwweight = 0.35;
double project1weight = 0.075;
double project2weight = 0.075;
double midtermweight = 0.20;
double finalweight = 0.25;
double totalgrade;
Scanner in = new Scanner(System.in);
System.out.println("What is your name? ");
name = in.nextLine();
System.out.println("What is your major? ");
major = in.nextLine();
System.out.println("What is your attendance grade (out of 100)? ");
attendance = in.nextInt();
System.out.println("What is your homework grade (out of 100)? ");
homework = in.nextInt();
System.out.println("What is your project 1 grade? ");
project1 = in.nextInt();
System.out.println("What is your project 2 grade? ");
project2 = in.nextInt();
System.out.println("What is your midterm grade? ");
midterm = in.nextInt();
System.out.println("What is your final grade? ");
finalexam = in.nextInt();
if(attendance > 100 || homework > 100 || project1 > 100 || project2 >100 || midterm > 100 || finalexam > 100) {
System.out.println("Your grade cannot exceed 100");
}
totalgrade = ((attendance * attweight) + (homework * hwweight) + (project1 * project1weight) + (project2 * project2weight) + (midterm * midtermweight) + (finalexam * finalweight));
if(totalgrade > 93 && totalgrade < 100){
finalgrade = "A";
}
if(totalgrade > 89 && totalgrade < 93){
finalgrade = "A-";
}
if(totalgrade > 86 && totalgrade < 90){
finalgrade = "B+";
}
if(totalgrade > 82 && totalgrade < 87){
finalgrade = "B";
}
if(totalgrade > 79 && totalgrade < 83){
finalgrade = "B-";
}
if(totalgrade > 76 && totalgrade < 80){
finalgrade = "C+";
}
if(totalgrade > 72 && totalgrade < 77){
finalgrade = "C";
}
if(totalgrade > 69 && totalgrade < 73){
finalgrade = "C-";
}
if(totalgrade > 59 && totalgrade < 70){
finalgrade = "D";
}
if(totalgrade < 60){
finalgrade = "F";
}
System.out.println("Your name is " + name + " and your major is " + major + ". Your attendance grade is " + attendance + ", your homework grade is " + homework + ", your project one grade is " + project1 + ", your project two grade is " + project2 + ", your midterm grade is " + midterm + ", your final exam grade is" + finalexam + ". Your total grade is " + totalgrade + " and your letter grade is " + finalgrade);
}
}
Error:
The local variable finalgrade may not have been initialized
EDIT: Elaboration
You already told us the problem. You need to initialize finalgrade. You did initialize it inside your conditional statements, however this is not guaranteed to happen when try to read the variable's value in your output (because the initialization only happens if you satisfy a condition) so the compiler gets mad. An easy work around would be to start out setting finalgrade to the empty string.
String finalgrade = "";
Also, look at your conditional statements. You're excluding 93, maybe other numbers. It would be better to use 'else if', after the first 'if' statement.
So I've used System.out.print("Enter more test scores? (y/n): "); yet when I run it and all the scores are summarizes the user isn't given the chance to do it again here is my code. Do you guys think I may have put it in the wrong place.
public class TestScoreApp
{
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
outerLoop:
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
if (setNumber == counter)
{
break outerLoop;
}
//End of test scores while loop
}
userAnswer = sc.next();
}
}// end of do loop
while(userAnswer.compareTo("y") == 0 );
System.out.print("Enter more test scores? (y/n): ");
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
}
I dont know what exactly you want to do, if you want to ask if the user want to add more scores after the default scores (that user set on beggining) so this is the answer:
import java.text.NumberFormat;
import java.util.Scanner;
public class TestScoreApp {
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// declarations
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
// outerLoop:
// do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999) {
do { // put the loop condition below
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100) {
scoreCount += 1;
scoreTotal += testScore;
setNumber--;
} // Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
// if (setNumber == counter) {
// break outerLoop;
// }
if (setNumber == counter) { // test if the counter reached zero
System.out.print("Enter more test scores? (y/n): "); // ask if the user want to add more
userAnswer = new Scanner(System.in).next(); // read the input
if (userAnswer.toCharArray()[0] == 'y') { // if yes, do
setNumber += 1; // add +1 to setNumber, so user can add more one score
}
}
} while (setNumber > 0);
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" + "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n" + "Average score: "
+ averageScore + "\n"
// Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n" + "Min score: " + min + "\n";
System.out.println(message);
}
}
There are several modifications to be done in the program.
When you are asking user to enter the choice for inputting more, you should accept his/her choice in your userAnswer variable before closing off the do-while loop SO THAT THE USER CHOICE CAN BE CHECKED AFTER EACH ITERATION!
There is no need to break the OUTER-LOOP without checking user's input!
scoreCount & scoreTotal need to be initialised with 0 again in the beginning of the do-while loop.
The corrected program along with the imports needed :-
import java.text.NumberFormat;
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreCount = 0,scoreTotal = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
scoreCount=0;
scoreTotal=0;
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
System.out.print("Enter more test scores? (y/n): ");
userAnswer=sc.next(); // Single Error----Only corrected piece of code.
}while(userAnswer.compareTo("y") == 0 );
// end of do loop
}
}
You are asking the user:
System.out.print("Enter more test scores? (y/n): ");
after you exit from the while loop. This won't work. Just put this line exactly before:
userAnswer = sc.next();