I was looking for some input on my code. What i'm trying to do is get user input in the form of scores on a test or something. The user can input how many grades they need to enter and it stores them on the array. Then the program will grade on a curve with the highest being an A. if a score is within 10 points of the highest score, it is also an A, if its in between 10 to 20 points less than the higher score its a B, if its 20 to 30 points less than the highest score then its a C, and so on till F.
My issue is that I don't know how to compare a certain element to the highest to see what grade it is. So my question is how do you compare a certain element in an array to the highest element in the array?
import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int students;
System.out.println("How many students do you have?");
students = keyboard.nextInt();
while (students < 0) {
System.out.println("Invalid student amount");
students = keyboard.nextInt();
}
int[] kids = new int[students];
double[] scores = new double[students];
for (int index = 0; index < students; index++) {
System.out.println("Enter score for student #" + (index + 1) + ": ");
scores[index] = keyboard.nextDouble();
}
double high = scores[0];
for (int index = 1; index < scores.length; index++) {
if (scores[index] > high) ;
high = scores[index];
}
if (//place in array >= (highest-10)
System.out.println("Student (whatever there position is) has an A")
}
}
So if anyone can give me some insight into this issue I'll be grateful, also if you see anything wrong with the code please tell me. Any help would be great. Just to clarify my issue is with trying to find the letter grade. look at the if statement at the bottom.
If I were you, I would do that in the following way:
public class Student implements Comparable{
int index;
private double grade;
public Student(int i, double d) {
grade = d;
index = i;
}
public int getIndex() {
return index;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
#Override
public int compareTo(Object o) {
Student s = (Student)o;
if (s.getGrade() < grade){
return -1;
} else if (s.getGrade() == grade) {
return 0;
}
return 1;
}
}
And the driver for the application is:
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int amount;
System.out.println("How many students do you have?");
amount = keyboard.nextInt();
while (amount < 0) {
System.out.println("Invalid student amount");
amount = keyboard.nextInt();
}
Student[] students = new Student[amount];
for (int index = 0; index < amount; index++) {
System.out.println("Enter score for student #" + (index + 1) + ": ");
students[index] = new Student(index, keyboard.nextDouble());
}
Arrays.sort(students);
for (int i = 0; i < amount / 10 + 1; i++) {
System.out.println("Student " + (students[i].getIndex() + 1) + " has an A");
}
}
Edit:
additional clarification for the OP asked in comments:
double highest = students[0].getGrade();
for (Student s : students) {
if (s.getGrade() > highest) {
highest = s.getGrade();
}
}
Related
my lecturer give me these question:
1. Write a program that does the following:
a. Get the number of students from user (n)
b. Ask user to enter n grades of n students, store them in an array.
c. Print out the max, the min, and the average of those n grades.
Note: write 3 methods to return the max/min/average element of an array
and use them in this program.
I try to do it, but the output of my program doesn't like what I'd expected.
Here is my code:
package javaapplication2;
import java.util.*;
public class JavaApplication2 {
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i;
}
}
return max;
}
public static double min(double[]y) {
double min = max(y);
for (int i =0; i < y.length; i++) {
if (y[i] < min) {
min = y[i];
}
}return min;
}
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
double grades [] = new double [5000];
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
}
And here is my output:
Enter student's name:
k
Enter student's score:30
The max grade is: 0.0
The min grades is: 0.0
Enter student's name:
Yah, I dont know why my max grade and min grade is 0.0. Anyone, please help me, thank you !!!
Your problem comes from the grade array s being reassigned each loop
public static void main(String[] args) {
String name ="";
String choice;
int times =0;
double score;
Scanner input = new Scanner(System.in);
System.out.println("Enter student's name: ");
name = input.nextLine();
while (name != "exit") {
//you set the grades array each loop to a new empty array
double grades [] = new double [5000]; //<--- Move this one out
System.out.println("Enter student's score: ");
score = Double.parseDouble(input.nextLine());
grades[times] = score;
times += 1;
System.out.println("The max grade is: " + max(grades));
System.out.println("The min grades is: " + min(grades));
System.out.println("Enter student's name: ");
name = input.nextLine();
}
}
Move it out and then try to get the methods done :)
Edit:
You also have a little error in the max method in regard of the value.
public static double max(double[]x) {
int i = 0;
int max=0;
for (i=0; i < x.length; i++) {
if (max < x[i]) {
max = i; //<-- Not max = i but max = x[i] :)
}
}
return max;
}
In the function where you are calculating max, you should use:
if (max < x[i]) {
max = x[i];
}
As you want to return the element and not it's index. Also you would want to declare your array named grades before the while loop or else it would create a new array on every iteration.
And for improving the code performance:
1. you can in your max/min functions, exit the loop as soon as you encounter a value=0. In your current code the loop iterates 5000 times even if there is a single entry.
2. in your min function instead of doing double min = max(y); you should use double min = Double.MAX_VALUE;. It will prevent the unnecessary calling of the max function.
I am given an integer, N, which is the number of test scores that will be inputted. For each line, N, there will be a student name followed their test score. I need to compute the sum of their test scores & print the the second-smallest student's name.
So, what I would do is create an array of classes for the students. The class would have two instance variables for the name and score. Then when all the input is done, all you need to do is get them. Here is the code that I came up with for that exact thing.
import java.util.*;
public class testScores {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Student[] students = new Student[n];
for(int i = 0; i < n; i++){
students[i] = new Student();
System.out.print("Enter the student's name");
students[i].setName(scan.next());
scan.nextLine();
System.out.print("Enter the student's score");
students[i].setScore(scan.nextInt());
scan.nextLine();
}
int total = 0;
int smallest_name = 0;
for(int i = 0; i < n; i++){
total+=students[i].getScore();
if(students[i].getName().length() < students[smallest_name].getName().length())
smallest_name = i;
}
int second_smallest = 0;
for(int i = 0; i < n; i++){
if(students[i].getName().length() > students[smallest_name].getName().length() && students[i].getName().length() < students[second_smallest].getName().length())
second_smallest = i;
}
System.out.println("The sum of the scores is: " + total);
System.out.println("The second smallest name is: " + students[second_smallest].getName());
}
}
class Student{
private String name;
private int score;
public Student(){}
public void setScore(int n){
score = n;
}
public void setName(String n){
name = n;
}
public int getScore(){
return score;
}
public String getName(){
return name;
}
}
import java.util.Scanner;
public class ClassAverage
{
public static void main(String args[])
{
String names[] = new String[50];
int scores[] = new int[50];
int entries = 0;
Scanner in = new Scanner(System.in);
//System.out.println("Enter number of entries");
//int entry = in.nextInt();
System.out.println("Enter the names followed by scores of students: ");
for(int i = 0; i < 50; i++)
{
names[i] = in.next();
scores[i] = in.nextInt();
entries++;
}
Average avg = new Average();
double average = avg.CalcAvg(scores,entries);
System.out.println("The class average is: " + average);
avg.belowAvg(scores,average,names,entries);
avg.highestScore(scores,names, entries);
}
}
class Average
{
Average()
{
System.out.println("The averages: ");
}
double CalcAvg(int scores[], int entries)
{
double avg;
int total = 0;
for(int i = 0; i < entries; i++)
{
total += scores[i];
}
avg = total/entries;
return avg;
}
void belowAvg(int scores[],double average,String names[], int entries)
{
for(int i = 0; i < entries; i++)
{
if(scores[i] < average)
System.out.println(names[i] + "You're below class average");
}
}
void highestScore(int scores[],String names[], int entries)
{
int max = scores[1];
for(int i = 0; i < entries; i++)
{
if(scores[i]>=max)
max=scores[i];
}
System.out.println("The maximum score is: " + max);
System.out.println("The highest score acheivers list: ");
for(int i = 0; i < entries; i++)
{
if(scores[i] == max)
System.out.println(names[i]);
}
}
}
im suppose to hold the ctrlkey press z and then press the enter key to end the program but how do i do that?
if you are wondering the program is to write a program that lets the user input student names followed by their test scores and outputs the class average, names of students below the average, and the highest test score with the name of student
Ctrl-Z is the DOS command code for end of input (the UNIX equivalent is Ctrl-D). All command line programs should support this because it allows you to pipe output from one as input to the other. Kudos to your teacher!
When this key combo is pressed, Scanner.hasNextLine() will return false. Here's an example of a loop that reads line until you hit Ctrl-Z on Windows (or Ctrl-D on Linux/Unix):
while (in.hasNextLine()) {
System.out.println("You wrote " + in.nextLine());
}
You can listen for the control-z character in your scanner:
String nextLine = in.nextLine();
if(nextLine.length == 1 && nextLine.charAt(0) == KeyEvent.VK_Z)
// end program
I have to make a program where you ask user to enter any number of students, that asks the name and grade of each student. So if I said 2 students, I would put billy smith, then 54, then it would ask me the name of the 2nd student, john smith, then the grade, 81. Then it outputs the names with grades in descending order of grades. It would output:
name---------grades
------------------
John smith 81
billy smith 54
I have evrything except for it printing it out. I need it to print out the name with the grade. Here is what I have:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
Double[] array = new Double[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] =input.next();
System.out.print("Enter the student's score: ");
array[i] = (Double) input.nextDouble();
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, Double[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
Double currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}
This is very similar to value base sorted map. The below provided solution would be helpful.
Sort a Map<Key, Value> by values (Java)
This is one way to do it, create a Student class to store name/grade pairs, and use Arrays.sort() with a custom Comparator to sort in descending order after all the input is read:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
//String[] names = new String[numofstudents]; //not needed
//Double[] array = new Double[numofstudents]; //not needed
Student[] students = new Student[numofstudents]; //added
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
//names[i] =input.next();
String student = input.next(); //added
System.out.print("Enter the student's score: ");
//array[i] = (Double) input.nextDouble();
Double grade = (Double) input.nextDouble(); //added
students[i] = new Student(student, grade); //added
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
//selectionSort(names, array);
Arrays.sort(students, new Comparator<Student>() {
#Override
public int compare(Student entry1, Student entry2) {
return entry2.grade.compareTo(entry1.grade); //sort by grade in descending order
}
});
//System.out.println(Arrays.toString(students));
for (int i = 0; i < students.length; i++){
System.out.println(students[i].student + "\t" + students[i].grade);
}
}
}
public class Student{
public String student;
public Double grade;
public Student(String s, Double g){
this.student = s;
this.grade = g;
}
}
So I'm supposed to create a program that asks for the class size. Then using that size, you enter a students name and score until you fill the class size. After doing that, I'm supposed to invoke a selectionSort method to sort the scores in descending order. So the output is essentially a table. One column is name, the other is score and the scores are supposed to be in descending order with their appropriate name. I have most of the program down, I just can't figure out how to tie the students name to their score that was entered. Can someone steer me in the right direct? I'm at a loss. Here is my program:
import java.util.Scanner;
public class Roster {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the size of the class: ");
int size = input.nextInt();
double[]score = new double[size];
String[]name = new String[size];
for(int i = 0; i < size; i++){
System.out.print("Please enter a student name: ");
String n = input.next();
name[i] = n;
System.out.print("Please enter " + n + "'s score: ");
double s = input.nextDouble();
score[i] = s;
System.out.println();
}
selectionSort(score,name);
System.out.print("THe class size is: " + size + "\n");
System.out.print("Name Score\n");
System.out.print("---- -----\n");
for(int i = 0; i < name.length; i++)
System.out.println(name[i] + " " + score[i] + " ");
System.out.println();
}
public static void selectionSort(double[] score, String[] name){
for(int i = score.length-1; i > 0; i--){
int maxIndex = 0;
for(int j = 1; j <= i; j++)
if(score[j] < score[maxIndex])
maxIndex = j;
double temp = score[i];
score[i] = score[maxIndex];
score[maxIndex] = temp;
}
}
}
I already commented a simple solution, but really the best thing to do would be to create a class of roster entries:
public class RosterEntry {
private String name;
private double score;
/*Accessors and Mutators*/
}
Then in your main you can maintain a list or array of RosterEntrys so that when you make swaps in the selection sort, you swap RosterEntrys instead of scores and names individually.
You could create a class of pairs, which you store in an array. As such:
public class MyPair
{
private final String name;
private final Double score;
public MyPair(String aName, Double aScore)
{
name= aName;
score = aScore;
}
public String getName() { return name; }
public Double getScore() { return score; }
}
You can then create a simple array of type MyPair,
MyPair[] pupils = new MyPair(20);
You can access details of pupils by
pupils[i].getName;
or
pupils[i].getScore;