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
Related
Trying to write a program where it outputs the user entered number if it is between 30 and 70.If not, it should prompt the user to reenter. This is what I have so far, but the code is not running at all.
What should I change?
I tried debugging but it seems like it just gives me random quick fixes that jumble up my original code.
here is the code:
package chpt5_project;
import java.util.Scanner;
public class chpt5_project {
//variables
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = input.nextInt();
while (count1 > 70 || count1 < 30){
System.out.println("Enter a value between 30 and 70: ");
input.close();
}
}
}
Move input.nextInt() into the while loop and don't close input until after the loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count1 = 0;
while (count1 > 70 || count1 < 30){
System.out.print("Enter a value between 30 and 70: ");
count1 = input.nextInt();
}
input.close();
}
// no need to close Scanner for System.in
Scanner scan = new Scanner(System.in);
// create an loop
while (true) {
System.out.print("Enter a value between 30 and 70: ");
int num = scan.nextInt();
// exit the loop if number is correct
if (num > 30 && num < 70)
break;
}
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;
}
}
}
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];
}
}
}
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);
}
}
}
When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}