I need to write an application to display the name and ID number of each student and to calculate whether they have passed or failed. I need to have 4 different classes student, studenttest, undergraduate, postgraduate.
So far this is what I have:
Student
class Student {
//private data members
private long idNumber = 0;
private String name = "Not Given";
private int markForMaths = 0;
private int markForEnglish = 0;
private int markForEconomics = 0;
private int markForPhilosophy = 0;
private int markForIT = 0;
//Default constructor
public Student() {
name = "Not Given";
idNumber = 0;
markForMaths = 0;
markForEnglish = 0;
markForEconomics = 0;
markForPhilosophy = 0;
markForIT = 0;
}
//Constructs a new Student with passed name and age parameters.
public Student(String studentName, long studentIdNumber) {
name = studentName;
idNumber = studentIdNumber;
}
//Returns the name of student.
public String getName( ) {
return name;
}
//Returns the idNumber of student.
public long getIdNumber( ) {
return idNumber;
}
//entermarks()
//enter all subject marks given as args
public void enterMarks(int maths, int english, int economics, int philosophy, int informationTechnology)
{
markForMaths = maths;
markForEnglish = english;
markForEconomics = economics;
markForPhilosophy = philosophy;
markForIT = informationTechnology;
}
//getMathsMark()
//return mark for maths
public int getMathsMark()
{
return markForMaths;
}
//getEnglishMark()
//return mark for English
public int getEnglishMark()
{
return markForEnglish;
}
//getEconomicsMark()
//return mark for Economics
public int getEconomicsMark()
{
return markForEconomics;
}
//getPhilosophyMark()
//return mark for Philosophy
public int getPhilosophyMark()
{
return markForPhilosophy;
}
//getITMark()
//return mark for IT
public int getITMark()
{
return markForIT;
}
//calculateAverageMark()
//return the average of the three marks
public double calculateAverageMark()
{
return ((markForMaths + markForEnglish +
markForEconomics + markForPhilosophy + markForIT) / 3.0);
}
//Sets the name of student.
public void setName(String studentName ) {
name = studentName;
}
//Sets the idNumber of student.
public void setIdNumber(long studentIdNumber ) {
idNumber = studentIdNumber;
}
}//end class
Undergraduate
public class Undergarduate extends Student{
}
Postgraduate
public class Postgraduate extends Student{
}
StudentTest
import java.util.Scanner;
public class StudentTest {
static int array;
//create method createArray
public static Student[] createArray() {
Scanner int_input = new Scanner(System.in);
//user enters size of array
System.out.print("Enter Size of Array: ");
array = int_input.nextInt();
Student[] array = new Student[0];
//read user input as arraySize
return new Student[5];
}//end method
//create method populateArray
public static void populateArray(Student[] array) {
Scanner string_input = new Scanner(System.in);
Scanner long_input = new Scanner(System.in);
Scanner int_input = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Student student = new Student(); // new student
//set name
System.out.println("Enter Student Name: ");
student.setName(string_input.nextLine());
//set ID number
System.out.println("Enter Student ID Number: ");
student.setIdNumber(long_input.nextLong());
//set Marks
System.out.println("Enter Marks");
student.enterMarks(int_input.nextInt());
//put new student into array passed to the method
array[i] = student;
}//end for loop
}//end method
//create method display Array
public static void displayArray(Student[] array){
System.out.println("Array Contents");
for (Student s : array) {
System.out.println(String.format("%s %d", s.getName(),
s.getIdNumber(), s.getEnglishMark(), s.getMathsMark(),
s.getEconomicsMark(), s.getPhilosophyMark(), s.getITMark(),
s.calculateAverageMark()));
}//end for loop
}//end method
public static void main(String [] args) {
// create array of size specified by user
Student[] students = createArray();
//populate this array with data from user
populateArray(students);
//display array contents
displayArray(students);
}//end main method
}//end class
I keep getting an error in the studenttest on the line
student.enterMarks(int_input.nextInt());
the error reads:
The method enterMarks(int, int, int, int, int, int) in the type Student is not applicable for the arguments (int)
As your class Student expects marks for each subject (english, maths, etc..), change your StudentTest class so that it passes each and every subject as input to enterMarks method.
Change your method call from:
student.enterMarks(int_input.nextInt());
TO
student.enterMarks(int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt());//to make it more readable and usable, first take input from keyboard by asking user to enter the number, assign to individual marks variable and then pass it to the method.
You are trying to invoke method enterMarks(int) but there is only enterMarks(int, int, int, int, int, int) method defined in Student class.
Related
just entered this community and this is my first question here, so please bear with a noob. I created two classes, first is Student, a basic one with fields, constructor and getters. The second one has the main method, a LinkedList, a multiple-entry Scanner (for...) and two simple methods.
My problem is that despite the fact that the For loop has maximum index 1 (x = 0; x < 2), the Scanner expects a third row input and an enter but does not print the third line. I add the two classes, maybe I made a mistake and I would appreciate your help. Thank you in advance.
public class Student {
private String name;
private String surname;
private int firstMark;
private int secondMark;
private int finalExamMark;
public Student(String name, String surname, int firstMark, int secondMark, int finalExamMark) {
this.name = name;
this.surname = surname;
this.firstMark = firstMark;
this.secondMark = secondMark;
this.finalExamMark = finalExamMark;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getFirstMark() {
return firstMark;
}
public int getSecondMark() {
return secondMark;
}
public int getFinalExamMark() {
return finalExamMark;
}
#Override
public String toString (){
return this.name + " " + this.surname + " got " + this.firstMark + " at English, " + this.secondMark + " at Math and " + this.finalExamMark + " at the final exam.";
}
}
public class StudentMain {
static LinkedList<Student> courseAttend = new LinkedList<>();
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
addStudent();
printList(courseAttend);
}
private static void addStudent() {
for (int x = 0; x < 2; x++) {
String s1 = scanner.nextLine();
String[] split = s1.split("\\s");
courseAttend.add(new Student(split[0], split[1], Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4])));
scanner.nextLine();
}
scanner.close();
}
private static void printList(LinkedList<Student> lista) {
for (Student elem : lista) {
System.out.println(elem);
}
}
}
For example, if I input (without quotes)
"Young John 9 9 9"
"Johnson Anne 8 8 8" and I press enter, the cursor moves to next line and waits another input. Only after that third line and the final enter, the message is displayed but the third line is not shown.
courseAttend should be a List<Student> courseAttend = new ...List<>(); like your methode argument printList(List<Student> students) because both could be also a ArrayList and it is the normal way to in implement variables if they have not to be sepciefied, like in your case.
The loop has two nextLine() but you ignore the second one so you are creating a student and waiting of the next input and not saving the input
When a User has to enter multiple arguments for any given prompt, you can expect to have typos. Your prompt expects the User to enter 5 arguments and they are not even from the same typ on a single line delimited with a whitespace. What if the user accidentally give you an ivalid input like a integer as name or a String as mark.
public class StudentMain {
static List<Student> courseAttend = new LinkedList<>();
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
for (int x = 0; x < 2; x++) {
courseAttend.add(createStudent());
}
scanner.close();
printList(courseAttend);
}
private static Student createStudent(){
System.out.print("name: ");
String name = scanner.nextLine();
System.out.print("surname: ");
String surname = scanner.nextLine();
System.out.print("first mark: ");
int firstMark = scanner.nextInt();
System.out.print("second mark: ");
int secondMark = scanner.nextInt();
System.out.print("final exam mark: ");
int finalExamMark = scanner.nextInt();
return new Student(name, surname, firstMark, secondMark ,finalExamMark);
}
private static void printList(List<Student> students) {
for (Student elem : students) {
System.out.println(elem);
}
}
}
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I have an ArrayList in main and I have a class with a constructor inside it and a method to print the data. I add a new object with new information, when called, and adds it to the ArrayList to keep it in one place. What I'm having a hard time is the syntax to print the information. I tried it with a regular array but I need to use ArrayList. I need to be able to get the index of a specific object, and print that object's information. For example, the code below the last couple lines:
import java.util.ArrayList;
import java.util.Scanner;
public class student{
String name;
int age;
int birthYear;
public student(String name, int age, int birthYear){
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public void printStudentInformation(){
System.out.println(name);
System.out.println(age);
System.out.println(birthYear);
}
}
public class Main{
public static void main(String[] args){
ArrayList listOfObj = new ArrayList();
ArrayList names = new ArrayList();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++){
System.out.println("New Student Information:"); // Three student's information will be saved
String name = sc.nextLine();
int age = sc.nextInt();
int birthYear = sc.nextInt();
student someStudent = new student(name, age, birthYear);
listOfObj.add(someStudent);
names.add(name);
}
System.out.println("What student's information do you wish to view?");
for(int i = 0; i < names.size(); i++){
System.out.println((i + 1) + ") " + names.get(i)); // Prints all students starting from 1
}
int chosenStudent = sc.nextInt(); // Choose a number that correlates to a student
// Should print out chosen student's object information
listOfObj.get(chosenStudent).printStudentInformation(); // This is incorrect, but I would think the syntax would be similar?
}
}
Any help or clarification is greatly appreciated.
You need to change your definition of listOfObj from:
ArrayList listOfObj = new ArrayList();
to:
ArrayList<student> listOfObj = new ArrayList<>();
The first will will create a ArrayList of Object class objects.
The second will create a ArrayList of student class objects.
Few more problems in your code:
Since you are reading name using nextLine, you may need to skip a new line after reading the birth year like:
...
int birthYear = sc.nextInt();
sc.nextLine(); // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
You select an option for the student to display, but that option is 1 indexed and ArrayList stores 0 indexed, so you should change the line to sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
Scanner may throw exception in case you enter, for example, a string instead of an int. So make sure you are handling exceptions properly using try-catch blocks.
You change the ArrayList defination and add toString() in your studen
class.
And to print all the student object insted of using for loop use just
one sop.
EX:-
import java.util.*;
class Student {
private String name;
private int age;
private int birthYear;
public Student() {
super();
}
public Student(String name, int age, int birthYear) {
super();
this.name = name;
this.age = age;
this.birthYear = birthYear;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
#Override
public String toString() {
return "Student [age=" + age + ", birthYear=" + birthYear + ", name=" + name + "]";
}
}
public class DemoArrayList {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
scan.nextLine();
String name = scan.nextLine();
int age = scan.nextInt();
int birthYear = scan.nextInt();
list.add(new Student(name, age, birthYear));
}
System.out.println(list);
}
}
O/P:-
2
joy
10
2003
jay
20
2005
[Student [age=10, birthYear=2003, name=joy], Student [age=20, birthYear=2005, name=jay]]
I am working on a java code where it should prompt the user to input the grades of N amount of students and it should output the highest grade, My code is working well but I want to give the user ability to enter the content of the array and I want to create a data type called Student for example for the array.
public class Test3 {
static double grades[] = {85, 99.9, 78, 90, 98};
static double largest() {
int i;
double max = grades[0];
for (i = 1; i < grades.length; i++)
if (grades[i] > max)
max = grades[i];
return max;
}
public static void main(String[] args)
{
System.out.println("Highest grade is : " + largest());
}
}
Any help would be really appreciated.
First, you should create the Student class:
public class Student {
private double grade;
// empty constructor
public Student() {}
// all args constructor
public Student(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" +
"grade=" + grade +
'}';
}
}
To avoid repetitive code, you can use the Lombok library. It creates for you the constructors, getters, setters, toString(), and much more.
After, you can create a method to input students grades.
public static Student[] inputStudens() {
Scanner sc = new Scanner(System.in);
System.out.println("How many students?");
int N = sc.nextInt();
Student[] students = new Student[N];
for (int i=0; i<N; i++) {
System.out.println("What's the grade for student " + i + ":");
double grade = sc.nextDouble();
Student student = new Student(grade);
students[i] = student;
}
return students;
}
And... using your already made max finder, but returning the Student instead.
public static Student maxGrade(Student[] students) {
int max = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() > students[max].getGrade()) {
max = i;
}
}
return students[max];
}
Now we just need to call these methods in main().
public static void main(String[] args) {
Student[] students = inputStudens();
Student student = maxGrade(students);
System.out.println("Student with highest grade is: " + student);
}
You can create an object and use that object to invoke the array to store value. For example:
test3obj= new Test3(); // creating an object.
Use test3obj to invoke the array to store values like:
test3obj.grades[i]=(object of scanner class).nextDouble();
Object of scanner class:
Scanner obj=new Scanner(System.in);
I have to create a code that takes user input for grades based on a students name that the user has inputted.
The input is to stop when a number less than 0 is inputted and the output should be the student name, the total of all the scores, and the average score.
For some reason I cannot get the average or the total to print, and my counter in my student class is showing an error "remove this token '++'"
Here is my main class, and my student class :
/**
* COSC 210-001 Assignment 2
* Prog2.java
*
* description
*
* #author Tristan Shumaker
*/
import java.util.Scanner;
public class main {
public static void main( String[] args) {
double[] addQuiz = new double[99];
int counter = 0;
//Creates new scanner for input
Scanner in = new Scanner( System.in);
//Prompts the user for the student name
System.out.print("Enter Student Name: ");
String name = in.nextLine();
// requests first score and primes loop
System.out.print("Enter Student Score: ");
int scoreInput = in.nextInt();
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
counter++;
}
System.out.println( );
System.out.println("Student name: " + name);
System.out.printf( "\nAverage: %1.2f", total(addQuiz, counter) );
System.out.printf( "\nAverage: %1.2f", average(addQuiz, counter) );
}
}
and my student class:
public class Student {
private String name;
private int total;
private int counter;
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void addQuiz( int scoreInput) {
total += scoreInput;
int counter++;
}
public static double average( double[] addQuiz, int counter ) {
double sum = 0;
for( int t = 0; t < counter; t++) {
sum += addQuiz[t];
}
return (double) sum / counter;
}
}
Any help you guys are able to give would be greatly appreciated, thanks in advanced.
change int counter++; in the addQuiz() method to just counter++;, as otherwise you're trying to declare a variable with identifier counter++ which is not a valid identifier. Also since you've declared average() to be a static method on the Student class you'll need to call it like so:
Student.average(addQuiz, counter);
I'm not seeing a definition for total() in your code so I don't know if the same would apply to that.
EDIT
To answer why average() is returning zero, it looks like you never set any values in the addQuiz double array that you're passing in, so it will contain all zeros, and as a result sum will be 0. I think what you want to do is to change your while loop in the main method to put the scoreInput value in the array at the counter index like so:
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
addQuiz[counter] = scoreInput;
counter++;
}
In your main class you are not using your Student class at all.
Consider doing
Student student = new Student (name);
and then using the methods such as
student.addQuiz (scoreInput);
and later
student.getTotal ();
etc.
You also do not need to store the variable counter in the Student Object at all as it is being passed as a parameter.
I have a Student class which has;
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i=0;i<array.length().i++) {
array[i] = new Student();
System.out.println("Enter student name: ");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry.next());
System.out.println("Enter student ID number: ");
array[i].setIDNumber(userInputEntry .nextLong());
}
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
}
}
How do I print the contents of the array back out to the user?
in class Student u can override toString():
#Override
public void toString(){
return "name: " + this.name;
}
and create a simple for loop
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
hope this helps a little
Override the toString method in Student class and then use https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])
use this in you display function if you don't want to override the toString method
for (int i = 0; i < array.length; i++) {
System.out.println("Student id : "+array[i].getIdNumber() + " Student name : " +array[i].getName());
}