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");
}
Related
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
}
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);
}
}
}
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);
}
}
I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.
can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];