I have created a program to check for input range for integer variable "paycategory" but when I want to check for inputmismatch errors as well. I tried it but its not working... I don't want to change the data type to string because the paycategory is supposed to be integer. Please help how to fix this problem ?
import java.util.Scanner;
import java.util.*;
import java.text.*;
import java.lang.Object.*;
public class TestEmployeePayRoll {
public static void main(String Args[])
{
String EmployeeID = null, FirstName = null, LastName = null, result;
double HoursWorked;
int PayCategory = 0, counter = 0;
do
{
Scanner input = new Scanner(System.in);
try
{
int flag = 1;
String input1 ;
System.out.println("Enter your Employee ID number: ");
while(flag==1){
EmployeeID = input.nextLine();
if(EmployeeID.trim().length()>=5){
flag = 0;
System.out.println("Enter the First Name: ");
FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
LastName = input.nextLine();
}else
System.out.print("EmployeeID must be exactly 5 digits long: \n Enter the Employee ID again: ");
}
}
catch(Exception e)
{
System.out.println("Exception ");
}
try{
do{
System.out.println("Enter the Pay Category: "+ " ");
PayCategory = input.nextInt();
if(!(PayCategory >0 || PayCategory <5))throw new InputMismatchException();
{
System.out.println("Pay Category must be between 1 and 4");
}
}
while(PayCategory < 1 || PayCategory > 4);
}
catch(InputMismatchException e)
{
System.out.println("PayCategory must be integers");
}
do
{
System.out.println("Enter the number of hours worked: ");
HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if(hours.isNaN())
{
System.out.println("---Enter a valid hours value---");
}
else if(!(HoursWorked >1 || HoursWorked <80))
{
System.out.println("---Enter value between 1 and 80---");
}
}
while(HoursWorked < 1 || HoursWorked > 80);
EmployeePayRoll obj1 = new EmployeePayRoll(FirstName, LastName, EmployeeID, HoursWorked, PayCategory);
DecimalFormat fmt = new DecimalFormat("###,##0.00");
System.out.println("\n-----------------------------------------------------");
System.out.println("\n The pay details for:" + obj1.getName() + "\t\t\t" + "ID:" + EmployeeID);
System.out.println("\n-----------------------------------------------------");
System.out.println("Pay Category: \t\t\t" + obj1.getPayCategory());
System.out.println("Hours Worked: \t\t\t" + obj1.getHoursWorked());
System.out.println("Pay Rate: \t\t\t" + obj1.getPayRate());
System.out.println("Gross Pay: \t\t\t" + "$"+fmt.format(obj1.getGrossPay()));
System.out.println("Tax Payable: \t\t\t" + "$"+fmt.format(obj1.getTaxPayable()));
System.out.println("\t\t\t\t---------");
System.out.println("Net Pay: \t\t\t" + "$" + fmt.format(obj1.getNetPay()));
System.out.println("\n------------------------------------------------------");
System.out.println();
System.out.println("\n Process another employee? (Y/N)");
result = input.next();
}
while (result.equals("Y")||result.equals("y"));
}
}
Thanks
Your condition below can never be true, so the InputMismatchException will never be thrown.
if(!(PayCategory >0 || PayCategory <5))
throw new InputMismatchException();
Correct your condition.
Read up on De Morgan's laws.
!(PayCategory >0 || PayCategory <5) is equivalent to !(PayCategory>0) && !(PayCategory<5).
Dogbane is quite correct in his answer but this problem is common in your code: you are over complicating your logical conditions which is making errors harder to spot.
Take the line:
else if (!(HoursWorked > 1 || HoursWorked < 80))
HoursWorked will ALWAYS be either > 1 or < 80 so the bracketed condition will ALWAYS be true and the reverse never. Try to make your logical conditions simpler so that you can easily see what they are rather than using the ! operator when it really isn't necessary.
This condition should be:
else if (HoursWorked < 1 || HoursWorked > 80)
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");
}
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.
I need this code to loop for however many iterations someone decides to use, I do not understand what condition I would need to put into the {while**(??here??)**;
Also I understand that the loop should go around my input statements and tax computation, have I placed the do and the while in the right position?
EDIT* I've removed 2 of the cases from the code which are pretty much the same so I could post within the rules here.
import java.util.Scanner;
public class Assignment333 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter your first name:");
String name = input.next();
System.out.println("Enter your age in years:");
byte age = input.nextByte();
System.out.println("Enter your gender (F/M):");
char gender = input.next().charAt(0);
System.out.println("Enter your marital status (S/M/D/W):");
char marital_status = input.next().charAt(0);
System.out.println("Enter your taxable income for 2016:");
long income = input.nextLong();
String name_prefix;
double tax_amount;
if (gender == 'M') {
name_prefix = (age < 18) ? "Master." : "Mr.";
} else {
name_prefix = (marital_status == 'M') ? "Mrs." : "Ms.";
}
switch (marital_status) {
case 'M':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * 0.01;
} else {
tax_amount = income * 0.025;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
break;
case 'W':
if (income < 8500) {
tax_amount = 0;
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe no tax for the fiscal year 2016");
} else {
if (income < 24000) {
tax_amount = income * .015;
} else {
tax_amount = income * 0.034;
}
System.out.println(name_prefix + " " + name + ", based on the income provided, you owe a tax of $" + tax_amount + " for the fiscal year 2016");
}
while ()
}
break;
default: System.out.println("Sorry! Our system is unable to calculate your tax at this time.");
}
System.out.println("Thank you!");
//closing all objects
input.close();
}
}
You can finish it like this:
...
System.out.println("Would you like to try again? (y/n)");
} while (Objects.equals("y", input.next()))
...
I have attempted using a nested if in the following code. I have initialized variables but the compiler is telling me that the variable named 'bill' is not initialized even though it has been. Why is the compiler not recognizing the value assigned to the variable? Please see the notes in the code below.
package killMe;
import java.util.Scanner;
public class Kill_Me {
static Scanner console = new Scanner(System.in);
static double PREMIUM_SERVICE = 55.00;
static double PREMIUM_DAY_OVERTIME_MIN = 0.20;
static double PREMIUM_NIGHT_OVERTIME_MIN = 0.15;
static double REGULAR_SERVICE = 30.00;
static double REGULAR_OVERTIME_MIN = 0.40;
public static void main(String[] args) {
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
} // End of class
No, bill has not been initialized in all cases.
Understand this: the Java compiler will never, ever, evaluate boolean expressions; Simplified version:
double bill;
if (c1) {
bill = v1;
} else if (c2) {
bill = v2;
}
// try and use bill here
Even if, according to your logic, boolean expressions c1 and c2 may cover all possible cases, the compiler cannot ensure that this is the case.
This is the root cause of your error, however deep your if/else, switch, etc statements may be nested.
They were some problems with else statement and variable declarations.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double PREMIUM_SERVICE = 25.00;
double PREMIUM_DAY_OVERTIME_MIN = 0.10;
double PREMIUM_NIGHT_OVERTIME_MIN = 0.05;
double REGULAR_SERVICE = 10.00;
double REGULAR_OVERTIME_MIN = 0.20;
int acctNumber;
double premiumDayMin;
double premiumNightMin;
double bill = 0.0;
double minutes;
String name;
String premium = "PREMIUM";
String regular = "REGULAR";
System.out.println("What is the Account Number? ");
acctNumber = console.nextInt();
System.out.println("What is the Customer Name? ");
name = console.next();
System.out.println("Is the Service Code Premium or Regular? ");
String strService = console.next();
String strServiceCAP = strService.toUpperCase();
if(strServiceCAP.compareTo(premium) == 0)
{
System.out.println("How many Day Minutes were used? ");
premiumDayMin = console.nextDouble();
System.out.println("How many Night Minutes were used? ");
premiumNightMin = console.nextDouble();
if(premiumDayMin <0 && premiumNightMin <0)
{
System.out.println("Minutes cannot be less than 0 ");
}
else if(premiumDayMin <= 75 && premiumNightMin <= 100)
{
bill = PREMIUM_SERVICE;
}
else
{
bill = PREMIUM_SERVICE + (premiumDayMin - 75) * PREMIUM_DAY_OVERTIME_MIN + (premiumNightMin - 100)
* PREMIUM_NIGHT_OVERTIME_MIN;
}
minutes = premiumDayMin + premiumNightMin;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Premium Service Used (Day): " + premiumDayMin);
System.out.println("Minutes Premium Service Used (Night): " + premiumNightMin);
System.out.println("Amount Due: " + bill); // I get an error here stating, "The local variable 'bill' may not have been initialized".
}
else if(strServiceCAP.compareTo(regular) == 0)
{
System.out.println("How many minutes were used? ");
minutes = console.nextDouble();
bill = REGULAR_SERVICE + (minutes - 50) * REGULAR_OVERTIME_MIN;
System.out.println("Customer Name: " + name);
System.out.println("Account Number: " + acctNumber);
System.out.println("Service Type: " + strServiceCAP);
System.out.println("Minutes Regular Service Used: " + minutes);
System.out.println("Amount Due: " + bill); // I DO NOT receive an error message here.
}
else
{
System.out.println("Invalid Service Type");
}
} // End of main
}
I'm not sure why it gets this error, but try initialising bill as 0.00 when you declare the variable.
Also,
if(premiumDayMin <0 && premiumNightMin <0)
should probably be changed to
if(premiumDayMin <0 || premiumNightMin <0)
Because you want to make sure that either minutes is not less then zero. You're program should then probably handle this error, because the rest of the program still executes. But maybe you're getting on to that :-P.
I don't recall what I did to stop getting an error message (sorry) but I removed the code if(premiumDayMin <0 && premiumNightMin <0) and replaced it with if(premiumDayMin <= 75 && premiumNightMin <= 100) to stop the code from being redundant. That may have fixed things. I also added another else if to clean the logic up further.
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.