How to display the "Invalid numbers with conditions" in Java? - java

Here is the problem with my output:
Enter number of students: 3
Enter the grade for student 1:
-2
Invalid grade, try again...
Enter the grade for student 2:
-3
Invalid grade, try again...
Enter the grade for student 3:
110
Invalid grade, try again...
The average is 35.0
But in the sample output session as follow:
Enter number of students: 3
Enter the grade for student 1:
55
Enter the grade for student 2:
108
Invalid grade, try again...
Enter the grade for student 2:
56
Enter the grade for student 3:
57
The average is 56.0
Can you see the -2, the -3 and 110 did not break the loop and it kept asking for new input? Instead of showing 108 on the sample and immediately break the loop and ask user to prompt the input of student 2 again.
Here is my code:
public static int theSumOfGrade(int[] newArray, int grade) {
int sumGrade = 0;
for(int i = 0; i < newArray.length; i++) { // for i < array length
sumOfGrade += newArray[i]; // the sum will be added up with all the values inside the array
}
return sumOfGrade;
}
public static int[] getNumberOfStudentsArray(Scanner input) { // Number of students input method
System.out.printf("Enter number of students: "); // Prompt the number of students from the user
int numberOfStudents= input.nextInt(); // Scanner Object in with numberOfStudents variable
int studentGrades[] = new int[numberOfStudents]; // Assign to new Array
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the grade for student " + (i+1) + ":" );
studentGrades[i] = input.nextInt();
// for (int j = 0; j < studentGrades.length; j++) {
// }
if (studentGrades[i] < 0 || studentGrades[i] > 100) {
System.out.println("Invalid grade, try again");
continue;
}
}
return studentGrades;
} // end of getNumberOfStudentsArray()

When the input is wrong then int i should not get the increment. So you can do it as below:
for (int i = 0; i < numberOfStudents;) { // removed increment from here
System.out.println("Enter the grade for student " + (i+1) + ":" );
studentGrades[i] = input.nextInt();
if (studentGrades[i] < 0 || studentGrades[i] > 100) {
System.out.println("Invalid grade, try again");
continue;
}
i++; // Increment only when entered value is correct
}

Related

How to show only the grades

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");
}

How to correct my sentinel value?

My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry.
Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import java.util.Scanner;
/**
*
* #author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();
System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}
Solution:
You get input from user and saving that input in varible called number but you are checking your while against inputNumber.
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
inputNumber = scan.nextInt(); <<< not number should be inputNumber
}
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
do {
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
if(inputNumber!= SENTINEL){
total+=inputNumber;
}
} while (inputNumber != SENTINEL);
System.out.println("The total is " + total);
}
}

Guidance needed for Invalid input error and collaborative class statistics for Grade Calculator

I am building a grade calculator in Java, I am having trouble adding a couple features to it, and it appears that I keep mucking it up too while I try to make changes. I have been working on it all week, and started over in the book and the powerpoint slides, and I just feel like there are just some pieces I am still not getting.
I need to make sure the invalid scores, reenter error shows up everytime a negative score is inputted. And then I need to calculate the class statistics of Average, Lowest and Highest scores. So basically a collaboration of how ever much data was inputted which could be any number of exams or students.
Here is my code, please let me know if you need more info. I am really new to this so I apologize that it is not the greatest.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args){
double examAverage = 0, scoresEntered = 0, examSum = 0;
double totalExamSum = 0, allScoresEntered = 0;
//variables for input
Scanner GC = new Scanner(System.in);
//Scanner for integer inputs
System.out.println("Welcome to Grade Calculator!" +"\n");
System.out.println("Please enter the number of students:");
int numberStudents = GC.nextInt();
//number of students input
System.out.println("Please enter the number of exams:");
int numberOfExams = GC.nextInt();
//number of exams input
for (int i = 1; i <= numberStudents; i++) {
Scanner name = new Scanner(System.in);
//scanner for student name input
//Scanner for name input
System.out.println("\n--------------------------------------");
System.out.print("Enter student " + i + "'s name : " );
String studentname = name.nextLine();
//student name input
System.out.print("Enter exam scores : ");
for (int j = 0; j < numberOfExams; j++) {
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);}
//score input and sum of all input scores
do{
System.out.println("Invalid exam scores, reenter: ");
scoresEntered =GC.nextDouble();
} while(scoresEntered<0);
//my attempt at the Invalid exam score error
examAverage = (examSum/numberOfExams);
//examaverage calculator
System.out.println("\n--------------------------------------");
System.out.println("Grade Statistics for " + name);
System.out.println(" Average : " + examAverage);
//Conditions and print outputs below for grade averages
if(examAverage <= 100 & examAverage >=90){
System.out.println(" Letter Grade: A");
System.out.println(" " + name + " gets 4 stars! ****");
examAverage = 0;
examSum = 0;}
else if(examAverage <=89.99 & examAverage >=80){
System.out.println(" Letter Grade: B");
System.out.println(" " + name + " " + " gets 3 stars! ***");
examAverage = 0;
examSum = 0;}
else if(examAverage <=79.99 & examAverage >=70){
System.out.println(" Letter Grade: C");
System.out.println(" " + name + " " + " gets 2 stars! **");
examAverage = 0;
examSum = 0;}
else if(examAverage <=69.99 & examAverage >=60){
System.out.println(" Letter Grade: D");
System.out.println(" " + name + " " + " gets 1 stars! *");
examAverage = 0;
examSum = 0;}
else if(examAverage <=59.99 & examAverage >=50){
System.out.println(" Letter Grade: F");
System.out.println(" " + name + " " + " gets 0 stars!");
examAverage = 0;
examSum = 0;}
//still need class statistics as well as help with the invalid exam scores, reenter error.
}
}
}
What jumps out at me is the looping around your score input:
for (int j = 0; j < numberOfExams; j++)
{
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);
}
//score input and sum of all input scores
do
{
System.out.println("Invalid exam score, reenter: ");
scoresEntered = GC.nextDouble();
} while(scoresEntered < 0);
I've deliberately reformatted what you posted to try to make the problem more obvious. What you appear to be doing is reading in all the scores. Then, regardless of what was entered, you tell the user the exam scores are invalid and ask them to re-enter. Remember, a do...while loop always executes at least once. If the first re-entered score is above zero, that is all you'll read as the while condition is then satisfied.
If you are trying to validate each score before it is added to examSum, you need something more like this:
for (int j = 0; j < numberOfExams; j++)
{
while ((scoresEntered = GC.nextDouble()) < 0)
System.out.println("Invalid exam scores, reenter: ");
examSum = (examSum + scoresEntered);
}

I'm new to java and I am working on a project, but I can't seem to get the for loop right

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to GradeCalculator!");
System.out.println("\nPlease enter the number of students: ");
int numberOfStudent = s.nextInt();
System.out.println("Please enter the number of exams: ");
int numberOfExams = s.nextInt();
System.out.println();
//outer loop for the number of students
for (int i = 1; i <= numbeOfStudent; i++) {
System.out.println("----------------------------------------");
System.out.println("Enter student " + i + "'s " + "name: ");
String name = s.nextLine();
s.next();
}
System.out.println();
//inner loop for the number of exams scores entered
int sum = 0;
for (int j = 1; j <= numberOfExam; j++) {
System.out.print("Enter exam scores: ");
double examScore = s.nextDouble();
sum += examScore;
if (examScore < 0) {
System.out.println("Invalid exam scores, reenter: ");
double examScoreReenter = s.nextDouble();
sum += examScoreReenter;
} else {
System.out.println();
}
}
}
console output :
Welcome to GradeCalculator!
Please enter the number of students:
2
Please enter the number of exams:
3
----------------------------------------
Enter student 1's name:
john smith
----------------------------------------
Enter student 2's name:
jane smith
Enter exam scores: "get exception"
------------------------------------------------------------------------
I've been struggling with this for days now and I cannot figure it out. The output I want is this:
-------------------------
Enter student 1's name :
Enter exam score:
Invalid exam scores, reenter:
-------------------------
Any suggestions would be greatly appreciated.
If you enter a non-valid double, such as "thisisastringnotanumber", an InputMismatchException is thrown. You should surround your nextDouble() call with a try block to accomidate for this.
for (int j = 1; j <= numberOfExam; j++) {
System.out.print("Enter exam scores: ");
try{
double examScore = s.nextDouble();
if (examScore < 0) {
System.out.println("Invalid exam scores, reenter: ");
j--; //Retry this iteration
} else {
sum += examScore;
System.out.println();
}
}catch(InputMismatchException e){
System.out.println("Invalid exam scores, reenter: ");
j--; //Retry this iteration
}
}

Java invalid entry counted

I am trying to figure out how not to include invalid entries from being counted.
I need to enter 5 scores and want "score count" to 5, but the code I made only enters 4 "score counts", including the invalid entry. I am not required to enter the invalid entry and have no idea on how to exclude the invalid entries from being counted as scores.
Here is the code below.
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
Scanner sc = new Scanner(System.in);
String choice = "y";
// get a series of test scores from the user
while (!choice.equalsIgnoreCase("n"))
{
// initialize variables
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
System.out.println("Enter the number of test score to be entered: ");
int numberOfTestScores = sc.nextInt();
for (int i = 1; i <= numberOfTestScores; i++)
{
// get the input from the user
System.out.print("Enter score " + i + ": ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
sc.nextLine();
// display the score count, score total, and average score
}
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.println();
System.out.println("Enter more test scores? (y/n)");
choice= sc.next();
}
}
}
Here is an example of the file being run.
Please enter test scores that range from 0 to 100. To end the
program enter 999. Enter the number of test score to be
entered: 5 Enter score 1: 66 Enter score 2: 85
Enter score 3: 99 Enter score 4: 79 Enter score 5: 457
Invalid entry, not counted
Score count: 4 Score total: 329 Average score: 82.0
Enter more test scores? (y/n)
Simply decrement the loop iteration variable i if it is an invalid score, so you re-ask for that score. So change this:
else if (testScore != 999)
System.out.println("Invalid entry, not counted");
to this:
else if (testScore != 999) {
System.out.println("Invalid entry, not counted");
i--;
}

Categories

Resources