Addition in Java program equals different value - java

I'm having a problem with this Java code. It's a questionnaire that should calculate your grade. It all goes and runs well until the very last part where it says "current score" that whole equation should equal 33.16 but instead it equals 24.
I changed some values, did some research but I haven't found what I'm looking for.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
System.out.println("Grading Scale:");
System.out.println("A\t 90 - 100");
System.out.println("B\t 80 - 89");
System.out.println("C\t 70 - 79");
System.out.println("D\t 60 - 69");
System.out.println("F\t below 60");
System.out.println("What letter grade do you want to achieve for the course?");
String desiredGrade;
Scanner keyboard = new Scanner(System.in);
desiredGrade = keyboard.next();
if (desiredGrade.equalsIgnoreCase("A") || desiredGrade.equalsIgnoreCase("B")
|| desiredGrade.equalsIgnoreCase("C") || desiredGrade.equalsIgnoreCase("D")
|| desiredGrade.equalsIgnoreCase("F")) {// is this necessary? vv
System.out.println("Enter Percentage Weights");
}
else {
System.out.println("Input error.");
System.exit(0);
}
int exam1, exam2, finalExam, labs, projects, attendance, quizzes;
System.out.println("Exam 1:\t");
exam1 = keyboard.nextInt();
System.out.println("Exam 2:\t");
exam2 = keyboard.nextInt();
System.out.println("Final Exam:\t");
finalExam = keyboard.nextInt();
System.out.println("Labs:\t");
labs = keyboard.nextInt();
System.out.println("Projects:\t");
projects = keyboard.nextInt();
System.out.println("Attendance:\t");
attendance = keyboard.nextInt();
System.out.println("Quizzes:\t");
quizzes = keyboard.nextInt();
// so the semicolon isn't needed after the if statement?
if (exam1 + exam2 + finalExam + labs + projects + attendance + quizzes != 100) {
System.out.println("Weights don't add up to 100, program exiting");
System.exit(0);
}
System.out.println("Enter your scores out of a 100:");
System.out.println("Do you know your Exam 1 score?");
String answer;
int exam1score = 0, exam2score = 0, finalExamScore = 0, labAverage = 0, projectAverage = 0, quizAverage = 0, attendanceAverage = 0;
double currentScore = 0;
answer = keyboard.next();
// ask about this
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
// why can't i put int here?
System.out.println("Score received on exam 1:");
exam1score = keyboard.nextInt();
System.out.println("Do you know your Exam 2 score?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on exam 2:");
exam2score = keyboard.nextInt();
System.out.println("Do you know your Final Exam score?");
answer = keyboard.next();
}
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Score received on final exam");
finalExamScore = keyboard.nextInt();
}
}
System.out.println("Do you know your lab average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Lab Grade:");
labAverage = keyboard.nextInt();
}
System.out.println("Do you know your project average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Project Grade:");
projectAverage = keyboard.nextInt();
}
System.out.println("Do you know your quiz average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Quiz Grade:");
quizAverage = keyboard.nextInt();
}
System.out.println("Do you know your attendance average?");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes") || answer.equalsIgnoreCase("y")) {
System.out.println("Average Attendance Grade:");
attendanceAverage = keyboard.nextInt();
}
currentScore = ((double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage)/((double)exam1+exam2+finalExam+labs+projects+attendance+quizzes);
System.out.println("Current Grade Score:\t " + currentScore);
String grade;
if (currentScore >= 90)
grade = "A";
else if (currentScore >= 80)
grade = "B";
else if (currentScore >= 70)
grade = "C";
else if (currentScore >= 60)
grade = "D";
else
grade = "F";
}
}

The following only converts the exam1score*exam1 value to double, not the entire expression.
(double) exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore + ....
So, you should do something like this.
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage;
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (double) nominator / denominator;
OR
int nominator = exam1score*exam1 + exam2score*exam2 + finalExam*finalExamScore
+ labs*labAverage + projects*projectAverage
+ attendance*attendanceAverage + quizzes*quizAverage);
int denominator = exam1 + exam2 + finalExam + labs + projects + attendance + quizzes;
currentScore = (nominator * 1.0) / denominator;

(double)exam1score*exam1 + exam2score*exam2 +finalExam*finalExamScore + labs*labAverage + projects*projectAverage + attendance*attendanceAverage + quizzes*quizAverage
only converts the first one to double and leaves the rest as int.

Related

How to set a limit in a for loop?

I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

Local variable may not be initialized

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.

How to get my program to start over when the user hits "y" on

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();

I'm having a issue with my while loop displaying two prints the second time around

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 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;
DecimalFormat df = new DecimalFormat("#0.0");
do {
System.out.print("Please enter the name of student " + student
+ ": ");
String line;
line = s.nextLine().toUpperCase();
names = line.split(" ");
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 (student == 1) {
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();
}
} else if (student == 2) {
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 + 4] = 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 + 4] = s.nextInt();
}
}
}
}
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
if (again.equalsIgnoreCase("y"))
student++;
} while (again.equalsIgnoreCase("y"));
System.out.println("***Class Results***");
System.out
.println(names[1]
+ ","
+ names[0]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[0] + exams[1] + exams[2] + exams[3]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 2)
;
System.out
.println(names[3]
+ ","
+ names[2]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[4] + exams[5] + exams[6] + exams[7]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 3)
;
System.out
.println(names[5]
+ ","
+ names[4]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[8] + exams[9] + exams[10] + exams[11]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
if (student == 4)
;
System.out
.println(names[7]
+ ","
+ names[6]
+ " "
+ "Exam Percentage: "
+ ((float) (exams[12] + exams[13] + exams[14] + exams[15]) / (MAX_EXAM * 3 + MAX_FINAL))
* 100 + "%");
}
}
My program seems to be running exactly the way i want/need it to, the only problem is, when i allow the program to run again it outputs two strings on the same line like this:
Please enter the name of student 2: Please enter score for Exam 1:
I don't know what to do to fix this. is there something in my code that messes up only on the second and probably 3rd and 4th times?
Remove semicolons after ifs
if (student == 3)
; // <- remove it
System.out.println(//...
because now Java understands it as
if (student == 3){}
System.out.println(//...
change
System.out.print("do you wish to enter another? (y or n) ");
again = s.next();
to
System.out.print("do you wish to enter another? (y or n) ");
again = s.nextLine();
next will not consume new line mark, so when you use nextLine after next it will consume only this new line mark and go to another instruction. Same rule apply for nextInt.
To store array of student names you could use two dimensional array of Strings
String[][] names = new String[MAX_STUDENTS][];
and store student names in each row based on student number
names[student] = line.split(" ");
To get first name of first student you will have to use this form
names[0][0]; //you probably know that indexes in array starts from zero
To get names of all students you can iterate over each rows and then over columns
for(int stId=0; stId<student; stId++){
for(int nameNumber=0; nameNumber<names[stId].length; nameNumber++){
// print names[stId][nameNumber]`
If you want the strings to print on a new line use println instead of print, or include a linebreak character in your string.

Categories

Resources