New variable for each user input in a loop - java

I am currently working on a program that takes a user input of the number of students in a class, then, (in a while loop), takes a user input of a student number and their average grade, then, after calculation, prints the highest mark, lowest mark, and average mark of the class.
This is what I have done so far:
import java.util.Scanner;
public class ClassMarks {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
while (x > 0) {
System.out.println("Enter student number: ");
double studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
double studentGrade = input.nextDouble();
x = x - 1;
}
}
}
I am looking for a way to get the program to create a new variable for me that stores each new user input student grade inside the while loop.
ex) studentGrade1, studentGrade2, studentGrade3 ...

Before the while loop, create variables highest/lowest grades
double highestGrade = Double.MIN_VALUE, lowestGrade = Double.MAX_VALUE;
double gradeSum = 0;
Then as you loop through the values, adjust the variables appropriately, e.g.
if (studentGrade > highestGrade)
highestGrade = studentGrade;
if (studentGrade < lowestGrade)
lowestGrade = studentGrade;
gradeSum += studentGrade;
And then after the loop finishes, get the average like this
double averageGrade = gradeSum / students;

How about using a List.
List<Student> students = new ArrayList<>()
and in while loop
create a student update its fields then add it to the list
Student myNewStudent = new Student();
// update fields
students.add(myNewStudent);
To iterate the list you can use a for loop.
for (Student s : students) {
// Get student info
}
Adapting this into your code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ClassMarks {
// Create an inner class Student
public static class Student {
public double studentNumber;
public double studentGrade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
// Create a list to hold your students
List<Student> studentsList = new ArrayList<>();
while (x > 0) {
Student myNewStudent = new Student();
System.out.println("Enter student number: ");
myNewStudent.studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
myNewStudent.studentGrade = input.nextDouble();
// update fields
studentsList.add(myNewStudent);
x = x - 1;
}
// Loop your student List
for (Student s : studentsList) {
// Get student info
System.out.println("Student number is: "+s.studentNumber+" grade is : "+s.studentGrade);
}
}
}

Related

Why won't my array pass to the other class?

I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}

Need help sorting ArrayList & Calculating averages of test scores

I tried adding a new class per a suggestion I was given, which is seen at line 67. I am unsure how to link the new class with the entries created from user input and the goal is to sort the ArrayList by the last name and to calculate averages of each of the entries 4 test scores, resulting in an average score - I would like the average score to be added to each students entry and added to the final ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
//information given by user input that will eventually go into the ArrayList
public class studentInformation {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Object> studentdatabase = new ArrayList<Object>();
char cont;
do {
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
//String fn = fnInput.nextLine();
studentdatabase.add(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
//String ln = lnInput.nextLine();
studentdatabase.add(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
//int score1 = score1Input.nextInt();
studentdatabase.add(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
//int score2 = score2Input.nextInt();
studentdatabase.add(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
//int score3 = score3Input.nextInt();
studentdatabase.add(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
//int score4 = score4Input.nextInt();
studentdatabase.add(score4Input.nextInt());
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//calculate the average score for each student
//sort the ArrayList prior to printing
//Collections.sort(studentdatabase);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' || cont != 'C');
}
class Students {
String firstName, lastName;
int firstScore, secondScore, thirdScore, fourthScore, averagescore;
char lettergrade;
}
}
Fisrt, create a real Student class (singular, not plural). An instance of this class is only one student. It will handle average calculation in a dedicated method.
Think about using getters and setters with the correct accessors on your attributes.
public class Student {
private String firstName, lastName;
private int firstScore, secondScore, thirdScore, fourthScore, averagescore;
private char lettergrade;
public float computeAverage(){
int sum = firstScore + secondScore + thirdScore + fourthScore;
return (float) sum / 4;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getFirstScore() {
return firstScore;
}
public void setFirstScore(int firstScore) {
this.firstScore = firstScore;
}
public int getSecondScore() {
return secondScore;
}
public void setSecondScore(int secondScore) {
this.secondScore = secondScore;
}
public int getThirdScore() {
return thirdScore;
}
public void setThirdScore(int thirdScore) {
this.thirdScore = thirdScore;
}
public int getFourthScore() {
return fourthScore;
}
public void setFourthScore(int fourthScore) {
this.fourthScore = fourthScore;
}
public int getAveragescore() {
return averagescore;
}
public void setAveragescore(int averagescore) {
this.averagescore = averagescore;
}
public char getLettergrade() {
return lettergrade;
}
public void setLettergrade(char lettergrade) {
this.lettergrade = lettergrade;
}
}
Then, don't use Object in your list but Student. You created an object. Use it !
You can't sort the list until you're done with feeding it. Put the sort out of the loop.
cont != 'c' || cont != 'C'
will always be true. So you will never get out of your loop.
Finally, I would suggest something like this.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Student> studentdatabase = new ArrayList<Student>();
char cont;
do {
Student currentStudent = new Student();
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
currentStudent.setFirstName(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
currentStudent.setLastName(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
currentStudent.setFirstScore(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
currentStudent.setSecondScore(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
currentStudent.setThirdScore(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
currentStudent.setFourthScore(score4Input.nextInt());
studentdatabase.add(currentStudent);
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' && cont != 'C');
//sort the arrayList prior to printing
studentdatabase.sort(Comparator.comparing(Student::getLastName));
//studentdatabase.sort(Comparator.comparing(Students::getLastName).reversed());
for (Student student:studentdatabase) {
System.out.println(student.getLastName() + " " + student.getFirstName() + " : " + student.computeAverage());
}
}
}

Java - Taking user input to create an unknown number of class objects/arrays/arrayLists

I need to allow the user to input any number of students. They press "C" to end data entry. I was thinking to make a student class (my code does not currently represent that) and 4 objects per student. Each set of 4 objects are the number grades that will be summed up and averaged.
I've already tried using a while loop, making arrayLists, and I've looked into maps. Each set of 4 grades corresponds to a student and must be summed and averaged separately.
package arrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> studentName = new ArrayList<String>();
ArrayList<Double> studentGrade = new ArrayList<Double>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String student = scanner.nextLine();
if(student.equals("C"))
{
break;
}
else
{
studentName.add(student);
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++) {
Double grade = Double.parseDouble(scanner.nextLine());
studentGrade.add(grade);
}
System.out.println(studentName);
System.out.print(studentGrade);
}
}
}
Problem here really is that I have all the entered numbers in one arrayList and I don't know if I can automatically create a new arrayList each time they enter a new student. Each arrayList would ideally hold just 4 double values.
Well please consider that grades are related to student and limited to always 4.
Therefore I suggest to implement a dynamic list of a class student with enclosed array of grades.
Example:
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> studlist = new ArrayList<Student>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String scanedline = scanner.nextLine();
if(scanedline.equals("C"))
{
break;
}
else
{
studlist.add(new Student(scanedline));
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++)
{
System.out.print(""+j+">");
Double scannedgrade = Double.parseDouble(scanner.nextLine());
studlist.get(studlist.size() - 1).grade[j]=scannedgrade;
}
System.out.println(studlist.get(studlist.size() - 1).name);
for (int j = 0; j < 4; j++)
System.out.print(studlist.get(studlist.size() - 1).grade[j] + " ");
System.out.println("");
}
}
private static class Student
{
String name;
Double [] grade;
Student (String s)
{
this.name = s;
grade = new Double[4];
}
}
}

Next Line problems with spacing

My program below prompts the user for how many children they have in their class. After entering the number they will enter all of the names of their students (first) and (last). Because of this I entered a scan Next Line statement instead of just scan.next. Because of this whatever number you enter the program will prompt you for one less. Please help.
public class studentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String [] students;
int size;
System.out.println("Enter the amount of students in your class: ");
size = scan.nextInt();
students = new String[size];
for (int i = 0; i < students.length; i++ ){
System.out.println("Enter a student name: ");
students [i] = scan.next();
}
System.out.println("Student Roster");
for ( int i = 0; i < students.length; i++ ){
System.out.println(students[i]);
}
}
}
Using scan.next() only captures up to the first space encountered, so you'll want to use .nextLine() if the user is entering both the first and last name at the same time.
To make this code work, add scan.nextLine(); after you assign sizeto the user input. Then, change students [i] = scan.next(); to students [i] = scan.nextLine();.
The reason you need to do this is because .nextInt() doesn't take in the last newline of the user's input, so you need to call .nextLine() to account for that.
public class StudentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String [] students;
int size;
System.out.print("Enter the amount of students in your class: ");
size = scan.nextInt();
scan.nextLine();
students = new String[size];
for (int i = 0; i < students.length; i++ ){
System.out.print("Enter a student name: ");
students [i] = scan.nextLine();
}
System.out.println("Student Roster");
for ( int i = 0; i < students.length; i++ ){
System.out.println(students[i]);
}
}
}
Test output
Enter the amount of students in your class: 4
Enter a student name: john Q
Enter a student name: albert E
Enter a student name: tyler D
Enter a student name: mickey M
Student Roster
john Q
albert E
tyler D
mickey M
the problem is this line
size = scan.nextInt();
becuase nextInt() method doesn't consume all the input buffer, it leaves the last (\n) character. When you call nextLine() after that it will not wait for the user to enter any thing but it will consume the (\n) character left in the buffer as a residue from the previous nextInt() method
so to correct this you have 2 options :
put additional scan.nextLine() directly after each scan.nextInt() method to consume the (\n)
size = scan.nextInt();
scan.nextLine();
students = new String[size];
//your code
Get the size as a string then convert it to int
String temp = scan.nextLine();
int size = Integer.parseInt(temp);
I suggest you to use an object better suited for your purpose (I think it's easier to hold data and improves readability):
import java.util.Scanner;
public class StudentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] students;
int size;
String name;
String lastname;
System.out.println("Enter the amount of students in your class: ");
size = scan.nextInt();
students = new Student[size];
Student student;
for (int i = 0; i < students.length; i++) {
student = new Student();
System.out.println("Enter a student name: ");
name = scan.next();
System.out.println("Enter a student lastname: ");
lastname = scan.next();
student.setName(name);
student.setLastname(lastname);
students[i] = student;
}
System.out.println("Student Roster");
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName());
System.out.println(students[i].getLastname());
}
}
static class Student {
String name;
String lastname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
}

input number of students java program

I need help making a program that will take the int input of the user as the number of students. At the moment I have to manually add the students in the code if I want more student. ive added my other class aswell. please help if possible.
import java.util.Scanner;
// the name of our class its public
public class ClassArray {
//void main
public static void main (String[] args){
//declare class
Student[] s = new Student[2];
s[0] = new Student();
s[1] = new Student();
//call functions
s[0].getdata();
s[1].getdata();
s[0].finalmark();
s[1].finalmark();
s[0].finalgrade();
s[1].finalgrade();
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
s[0].print();
s[1].print();
}
}
}
//declare class
public static class Student {
//declare variables.
private Double finalmark;
private int test1,test2,assignments1,finalexam;
private String studentname,finalgrade;
//functions should be public if needed to access from other class
public void getdata()
{
//print message to enter numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter name of student:");
studentname = input.next();
while (!studentname.matches("[a-zA-Z]+")) { // Checks to see if only letters are used in the name
System.out.println("Please re-enter your name, use alphabets only");
studentname = input.nextLine(); // if anything other than letters are used, the user must re-enter his/her name using letters
}
System.out.println("Enter mark test 1 for student:");
test1 = input.nextInt();
while (test1 > 100 || test1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next();
}
test1 = input.nextInt();
}
System.out.println("Enter mark test 2 for student:");
test2 = input.nextInt();
while (test2 > 100 || test2 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
test2 = input.nextInt();
}
System.out.println("Enter mark assignments for student:");
assignments1 = input.nextInt();
while (assignments1 > 100 || assignments1 < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
assignments1 = input.nextInt();
}
System.out.println("Enter mark final exam for student:");
finalexam = input.nextInt();
while ( finalexam > 100 || finalexam < 0){
System.out.println("Please enter a double value between 0 and 100");
while(!input.hasNextInt()){
input.next() ;
}
finalexam = input.nextInt();
}
}
public void finalmark(){
finalmark = (test1 * 0.15) + (test2 * 0.25) + (assignments1 * 0.25) + (finalexam *
0.35);
}
public void finalgrade()
{
if(finalmark >= 100)
finalgrade="A+";
else if(finalmark >= 90)
finalgrade="A+";
else if(finalmark >= 80)
finalgrade="A";
else if(finalmark >= 75)
finalgrade="B+";
else if(finalmark >= 70)
finalgrade="B";
else if(finalmark >= 65)
finalgrade="C+";
else if(finalmark >= 60)
finalgrade="C";
else if(finalmark >= 50)
finalgrade="D";
else
finalgrade="F";
}
public void print(){
System.out.printf("%s\t%.2f\t%s\t%d\t%d\t%d\t\t%d\n", studentname, finalmark,
finalgrade, test1, test2, assignments1, finalexam);
}
}
Something like this:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Your complete code would be:
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number of Students:\t");
int numStudents = Integer.parseInt(scanner.nextLine());
Student[] s = new Student[numStudents];
for(int i = 0; i < numStudents; i++ ){
s[i] = new Student();
s[i].getdata();
s[i].finalmark();
s[i].finalgrade();
}
System.out.printf("Name\tDefinitive\tLetter\tTest 1\tTest 2\tAssignments\tFinalExam \n");
//Here it will iterate and print out the stored data as soon as the user has finished adding it.
for(int j = 0; j < numStudents; j++ ){
s[j].print();
}
}
Simply,
import java.util.Scanner;
public class ClassArray {
public static void main (String[] args) {
Scanner input= new Scanner(System.in); // create Scanner object
System.out.print("Enter The Number of Students: ");
int numOfStudents = input.nextInt(); // input an integer value
// do whatever you like
}// Ends main
}
Here I created an object of class Scanner as input and I've called the method nextInt() by the object of class Scanner (input).
See this post for user input: How can I get the user input in Java?
You also should not use an array which you have defined as having a set number of elements, in your example 2. Instead, consider an ArrayList of objects type Student which for your purposes can accept any number of Students.
ArrayList<Student> s = new ArrayList<Student>();
//Example add student
Student student1 = new Student();
s.add(student1);
See this post for ArrayList: Java: ArrayList of String Arrays

Categories