public class Exams {
private int score1 = 0;
private int score2 = 0;
private int score3 = 0;
public void setScore1(int sc){
score1 = sc;
}
public void setScore2(int sc){
score2 = sc;
}
public void setScore3(int sc){
score3 = sc;
}
public int getScore1(){
return score1;
}
public int getScore2(){
return score2;
}
public int getScore3(){
return score3;
}
public String toString(){
return String.format("%-10s %-10s %4.2f\n", score1, score2, score3);
}
}
public class Student {
private String fName;
private String lName;
private Exams scores;
Student(String fn, String ln) {
fName = fn;
lName = ln;
scores = new scores();
}
public void setScore1(int sc) {
scores.setScore1(sc);
}
public void setScore2(int sc) {
scores.setScore2(sc);
}
public void setScore3(int sc) {
scores.setScore3(sc);
}
public String toSring(){
return String.format("%-10s %-10s %4.2f\n", fName, lName, scores);
}
public double getAverage(){
}
public int compareTo(Student s){
String name1 = lName + " " + fName;
String name2 = s.lName + " " + s.fName;
return ((lName + " " + fName).compareTo(s.lName + " " + s.fName));
}
}
public class ClassRoll {
private ArrayList<Student> students = new ArrayList<Student>();
private String title;
private String filename = "data.txt";
ClassRoll(String f) {
Scanner kb = new Scanner(System.in);
String inpFileName = kb.next();
File inpFile = new File(inpFileName);
Student s = new Student(fName, lName);
}
void Remove() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
students.remove(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void Display() {
}
void Add() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
System.out.println("What is the Student's second score?");
int score2 = kb.nextInt();
System.out.println("What is the Student's third score?");
int score3 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
System.out.println("Student already in class");
} else {
students.add(s);
}
}
}
void changeScore1() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore1(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void changeScore2() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore2(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
void changeScore3() {
Scanner kb = new Scanner(System.in);
System.out.println("What is the Student's first name?");
String fName = kb.next();
System.out.println("What is the Student's last name?");
String lName = kb.next();
System.out.println("What is the Student's first score?");
int score1 = kb.nextInt();
Student s = new Student(fName, lName);
for (int i = 0; i < students.size(); i++) {
if (s.compareTo(students.get(i)) == 0) {
s.setScore3(i);
} else {
System.out.println("Error: Student is not in Class");
}
}
}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}
}
}
public void sortNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}
}
public void save(){
}
}
I have a program with a couple of different classes. In the classroll class after I declare the private variables I have to create a classroll constructor "ClassRoll(String f)" that is suppose to .....
Read the class roll data from the input file f, creates Student objects for each of the students and adds them to the ArrayList of students. The input file contains the course title on the first line. The data for each student appears on a separate line consisting of first name, last name, score1, score 2, and score3 separated by at least one space.
I tried my best to start it off but I'm confused and don't really know the right way of making it. Can someone please help
Thank you
Read the class roll data from the input file f, creates Student
objects for each of the students and adds them to the ArrayList of
students.
Ok, so basically, we have to get student's information from some file and add it to some ArrayList. Alright, lets create an ArrayList for storing stuff first.
ArrayList<Student> studentInfo = new ArrayList<Student>();
You already have this code to read from file:
Scanner kb = new Scanner(System.in);
String inpFileName = kb.next();
File inpFile = new File(inpFileName);
Lets move on....
The input file contains the course title on the first line.
So first element in kb.nextLine() is the course title. This means that we have to start adding student data from second line aka skip the first line. Alright....
The data for each student appears on a separate line consisting of
first name, last name, score1, score 2, and score3 separated by at
least one space.
So basically, if we manage to split lines from space characters, we get data. Now to implement this:
Lets create a boolean variable to check if its first line or not:
boolean firstLine = true; // True - because it starts from first line
Time to start reading lines....
String courseName = ""; //I'll just store in a string, use as you wish
while(kb.hasNextLine()){
if(firstLine){
courseName = kb.nextLine(); //Set courseName if its first line
firstLine = false; // We have moved past first line
}
else{ // Otherwise get student data
// Lets store the student data in a string. This is just one line.
// Something like: "FirstName LastName score1 score2 score3"
String studentData = kb.nextLine();
// Now time to split up data (so we get names/scores separately)
String[] stData = studentData.split("\\s"); //Remember they have spaces between them. \\s --> A pattern that matches one or more spaces
//So we can use those to separate data
// This is how String[] stData contains the student information:
// stData[0] = first name of student
// stData[1] = last name of student
// stData[2] = score1
// stData[3] = score2
// stData[4] = score3
// Use this data however you like
//Now that we have separated data, lets add the student object to ArrayList since we got all details.
studentInfo.add(new Student(stData[0], stData[1]);
// This last line of code is probably not going to do the trick.
// You may need to make changes to your code to do stuff
}
}
In any case, I have told you how to read the problem and how to proceed. You have all the strings, the firstname, lastname and scores. Now its upto you to figure out how to use them. Although the last line of code may not work for your, but its a hint to proceed.
Rest you should try figure out yourself first, since its no fun if I do all the homework ;)
You have replaced the SE with the scire1,2,3
When you get a var in setter method it need to be placed in a property of your class.
Just replace with this code:
public void setScore1(int sc){
score1=sc;
}
public void setScore2(int sc){
score2=sc;
}
public void setScore3(int sc){
score3=sc;
}
Related
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
So, basically I have an assignment that requires for me to Write a java program to help maintain a class roll. The program must contain four classes: Student, Exams, ClassRoll and Assignment4(Main).
I have developed all the classes but the ClassRoll constructor it s not performing correctly. When I run the program I am prompted with the file name option, once i enter the file name I see null then the options to modify and / or display the list, but when I enter a command, it does not work, it gives me an error.
The Output should be
Expected input/output:
Assuming that the file data.txt contains:
COP2210
John Doe 50 60 70
Marco Boyle 50 60 73
Eric Munzon 45 100 90
Marry Able 95 100 100
Jack Smith 100 100 100
Elizabeth Gomez 100 100 100
The following is a sample input output run:
What is the name of input file: data.txt
Enter one of the following commands
a or add to add a student in the class roll
sa or average to sort the students based on their average
sn or names to sort the students based on their last names
r or remove to remove a student from the class roll
s or save to save the list of students back to the datafile
Here are my classes;
public class Student {
private String fName = "";
private String lName = "";
private Exam scores;
public Student(String f, String l){
fName=f;
lName=l;
scores = new Exam();
}
public void setScore1(int score) {
scores.setScore1(score);
}
public void setScore2(int score) {
scores.setScore2(score);
}
public void setScore3(int score) {
scores.setScore3(score);
}
public String toString() {
return lName + "\t" + fName + "\t" +
scores.toString();
}
public double getAverage() {
return (scores.getScore1() + scores.getScore2() +
scores.getScore3())/3.0;
}
public boolean equals(String f, String l) {
return f.equals(fName) && l.equals(lName);
}
public int compareTo(Student s){
if (lName.compareTo(s.lName) > 0)
return 1;
else if (lName.compareTo(s.lName) < 0)
return -1;
else if (fName.compareTo(s.fName) > 0)
return 1;
else if (fName.compareTo(s.fName) < 0)
return -1;
else return 0;
}}
public class Exam {
private int score1;
private int score2;
private int score3;
public Exam(){
score1=0;
score2=0;
score3=0;
}
public void setScore1(int score) {
score1=score;
}
public int getScore1() {
return score1;
}
public void setScore2(int score) {
score2=score;
}
public int getScore2() {
return score2;
}
public void setScore3(int score) {
score3=score;
}
public int getScore3() {
return score3;
}
public String toString() {
return Integer.toString(score1) + "\t"
+Integer.toString(score2)
+ "\t" + Integer.toString(score3) + "\t";
}}
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
Scanner fileScan, lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Title =" + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student s = new Student(firstName, lastName);
s.setScore1(lineScan.nextInt());
s.setScore2(lineScan.nextInt());
s.setScore3(lineScan.nextInt());
students.add(s);
//display(students);
ClassRoll c = new ClassRoll();
c.display();
}
}
void display() {
DecimalFormat fmt = new DecimalFormat("0.00");
System.out.println("\t\t\t" + title);
double classAverage = 0.0;
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
System.out.print(s.toString());
System.out.println("\t" + fmt.format(s.getAverage()));
classAverage = classAverage + s.getAverage();
}
System.out.println("\t\t\t" + fmt.format(classAverage /
students.size()));
}
public void insert() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
System.out.print("Score 1 -> ");
int score1 = input.nextInt();
System.out.print("Score 2 -> ");
int score2 = input.nextInt();
System.out.print("Score 3 -> ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
private int search(String f, String l) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(f, l)) {
return i;
} else {
i++;
}
}
return -1;
}
public Student find() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}}
public void delete() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student not found");
}
}
public void sortLastNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}}
public void save() throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
}
out.close();
}}
public class Assignment4bis {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.print("Enter the name of the input file ->");
String fileName=input.next();
ClassRoll c = new ClassRoll();
c.display();
prompt();
System.out.print("Enter a command --> ");
String ans=input.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (ans.charAt(0))
{
case 'i': c.insert();
break;
case 'a': c.sortAverage();
c.display();
break;
case 'n': c.sortLastNames();
c.display();
break;
case 'r': c.delete();
c.display();
break;
case 'f': Student s=c.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 'd': c.display();
break;
}
prompt();
System.out.print("Enter a command --> ");
ans=input.next();
}
c.save();
System.out.println("Thank you for using this program");
}
public static void prompt(){
System.out.println("Enter one of the following commands");
System.out.println("i or insert to insert a student in the class
roll");
System.out.println("a or average to sort the students based on
their average");
System.out.println("n or names to sort the students based on their
last names");
System.out.println("r or remove to remove a student from the class
roll");
System.out.println("f or find to find a student in the class
roll");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");
}}
Errors that I m still getting...
run:
Enter the name of the input file ->data.txt
Title =COP2210
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
Java Result: 1
Your ClassRoll "constructor" is a "pseudo-constructor":
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public void ClassRoll(String f) throws IOException {
Constructors have no return type, so get rid of the void:
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
As a bit of side recommendations:
You look to be mixing user interface with one of your "model" or logical classes, ClassRoll, something you probably shouldn't do. I'd keep all user interface code, including use of a Scanner and File I/O separate from ClassRoll, which likely should just have code to create the collection, to allow other classes to add or remove from the collection, and to allow other classes to query the collection.
Take care to learn and follow Java code formatting rules. You've got some deviations from the standard, including have your class declaration lines indented the same as the method body and variable declaration lines, bunching up of end braces,... This makes your code hard for other Java coders to read and understand.
I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.
I am working on my final and I got to the part I an mildly confused about.
I can't figure out if it's possible to call the Admin or Student inputs with it being outside of the if statement. I need to call the results in the 3rd and 4th option in the menu and I can't do it without it throwing errors.
public class MainEntry {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int printMenu = 0;
while(printMenu != 5){
printMenu();
printMenu = console.nextInt();
if (printMenu == 1){
String firstName;
String lastName;
int year;
double[] grades;
double studentId;
String major;
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
Student newStudent = new Student();
int[] stud = new int[size];
for(int i = 0; i < stud.length; i++)
{
System.out.println("What is the students first name? ");
firstName = console.next();
newStudent.setFirstName(firstName);
System.out.println("What is the students last name? ");
lastName = console.next();
newStudent.setLastName(lastName);
System.out.println("What year are they in? ");
year = console.nextInt();
newStudent.setYear(year);
System.out.println("Enter in their grades: ");
grades = console.nextDouble();newStudent.setGrades(grades);
System.out.println("What is their Student ID number? ");
studentId = console.nextDouble();
newStudent.setStudentID(studentId);
System.out.println("What is the student's major? ");
major = console.next();
newStudent.setMajor(major);
}
}
else if (printMenu == 2){
Admin newAdmin = new Admin();
System.out.println("How many admins do you have? ");
int size = console.nextInt();
int[] admins = new int[size];
for(int i = 0; i < admins.length; i++)
{
System.out.println("What is the admin's first name? ");
String firstName = console.next();
newAdmin.setFirstName(firstName);
System.out.println("What is the admin's last name? ");
String lastName = console.next();
newAdmin.setLastName(lastName);
System.out.println("What is their Admin's ID number? ");
double adminId = console.nextDouble();
newAdmin.setAdminId(adminId);
System.out.println("What is the Admin's department? ");
String department = console.next();
newAdmin.setDepartment(department);
System.out.println("What is their salary? ");
int salary = console.nextInt();
newAdmin.setsalary(salary);
}
}
else if (printMenu == 3){
System.out.println("First name: " + newStudent.getFirstName());
System.out.println("Last name: " + newStudent.getLastName());
System.out.println("ID Number: " + newStudent.getStudentID());System.out.println("GPA: " + newStudent.getgrade());System.out.println("Major: "+newStudent.getMajor());
}
else if (printMenu == 4){
System.out.println("First name: " + newAdmin.getFirstName());
System.out.println("Last name: " + newAdmin.getLastName()); System.out.println("ID Number: " + newAdmin.getAdminId()); System.out.println("GPA: " + newAdmin.getgrade());
System.out.println("Major: " + newAdmin.getsalary());
}
else if(printMenu == 5){
System.out.println("Thanks for using my program!");
}
}
}
// This method will bring up the beginning menu for the user
public static void printMenu(){
//Asking the user which option they are selecting
System.out.println("How would you like to input your data?");
System.out.println("1. Enter in students. ");
System.out.println("2. Enter in admins. ");
System.out.println("3. Print the student information. ");
System.out.println("4. Print admin information. ");
System.out.println("5. Exit the program. ");
}
}
For the student grade I need to average there 5 grades together using an array.
public class Student {
// stores the first name
private String firstName;
// stores the last name
private String lastName;
// stores the
private int year;
// stores the grades
private double[] grades;
// stores the ID number
private double studentID;
private String major;
public static int studentInfo;
//here is where it sets the defaults
public Student(){
firstName = "Jane";
lastName = "Doe";
year = 1;
grades = new double[]{0,0,0,0,0};
studentID = 0;
major = "undeclared";
studentInfo++;
}
public static int studentInfo(){
return (studentInfo);
}
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 getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double[] getGrades() {
return grades;
}
public void setGrades(double[] grades) {
this.grades = grades;
}
public double getStudentID() {
return studentID;
}
public void setStudentID(double studentID) {
this.studentID = studentID;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static int getStudentInfo() {
return studentInfo;
}
public static void setStudentInfo(int studentInfo) {
Student.studentInfo = studentInfo;
}
public Student(String firstName, String lastName, int year, double[] grades, double studentID){
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.grades = grades;
this.studentID = studentID;
studentInfo++;
}
}
I understand how to build it in the class side but I don't understand how to use it in MainEntry. It keeps asking me to change type and I can't figure out what else to do to fix it. I have issues with arrays so that's something that I'm not quite the best at...
Any help is appreciated.
1) For this, you need to declare newStudent outside of the if statement.
while(printMenu != 5){
Student newStudent = null; // ← newStudent is declared here
printMenu();
printMenu = console.nextInt();
This means that you don't declare it later, only assign to it the result of the new operator:
int size;
System.out.println("How many students do you have? ");
size = console.nextInt();
newStudent = new Student(); // ← this is only an assignment, not a declaration
It also means that you have to be careful when the user wants to display the information concerning the student, because newStudent can be null (i.e. no information have been entered yet).
2) The average is not a double array, just a double. This is why the compiler complains about incompatible types. The average will not be computed automatically, you have to do it yourself. Basically, you need two steps. First, iterate through the array and calculate the sum of the elements:
double sum = 0;
for (double g : grades) { // do this for all elements of the array
sum += g; // add the element to the sum
}
Then, the average is the sum divided by the number of elements.
double average = sum / grades.length;
I am trying to have the user type in the last name and first name of a student in an array so that I can call the student information and use it in a grade book.
The Student class has a method called Student(String last_name, String first_name)
I cannot figure out how to make it print students in a list such as:
last name, first name
last name, first name
Here is my program so far:
public static void main (String[] args)
{
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
students = GetNumberOfStudents();
//Allocate space for student information
Student student[] = new Student[students];
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
student[i] = scan.nextLine();
System.out.print("\tEnter first name: ");
student[i] = scan.nextLine();
}
System.out.println(student[i]);
I expect we would need to see the definition of Student, you have given the constructor but not the getters/setters.
I would expect the printing code to look something like
for (Student s : student) {
System.out.println(s.getLastName() + "," + s.getFirstName());
}
You are also not initialising your Student objects correctly.
Inside the loop you have written I would expect to see
new Student(lastname, firstname);
Here is a soltuion with a student class which looks like in your description.
package test; //change to your package name
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student{
private String m_LastName;
private String m_FirstName;
private int[] TestScores = new int[3];
//Constructor
public Student(String last, String first) {
m_LastName = last;
m_FirstName = first;
}
//returns firstname
public String firstName() {
return m_FirstName;
}
//returns lastname
public String lastName() {
return m_LastName;
}
//set a test score at a given index
public void setTestScore(int index, int score) {
TestScores[index] = score;
}
//returns test score at a given index
public int testScore(int index) {
return TestScores[index];
}
//returns testscores average
public double testAverage() {
int sum = 0;
for(int i = 0; i<TestScores.length; i++) {
sum += TestScores[i];
}
return sum/TestScores.length;
}
//returns students highest test score
public int maxTestScore() {
//sort the array
for(int i = 0; i<TestScores.length; i++) {
for(int j = 0; j<TestScores.length; j++) {
if(TestScores[i]<TestScores[j]) {
int buffer;
buffer = TestScores[i];
TestScores[i] = TestScores[j];
TestScores[j] = buffer;
}
}
}
return TestScores[TestScores.length-1];
}
public boolean isPassing() {
//TODO: when hes passing?
return true;
}
public static void main (String[] args)
{
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.println("--------------------------------");
System.out.println("Welcome to the Gradebook Program");
System.out.println("--------------------------------");
System.out.println();
/**
* dont know where you declare the students variable
* and how the getnumberofstudents function looks like
*
* students = GetNumberOfStudents();
*/
int students = 1;
List<Student> StudentList = new ArrayList<>(); //creat a list which can store student objects
for (int i = 0; i < students; i++)
{
System.out.println("Student #" + (i+1));
System.out.print("\tEnter last name: ");
String lastname = scan.nextLine(); //store lastname in a variable
System.out.print("\tEnter first name: ");
String firstname = scan.nextLine(); //store firstname in a variable
Student student = new Student(lastname, firstname); //creat new student object with the last and firstname
StudentList.add(student); //add it to the student list
}
//print out all students first and lastnames. here you can add the other data you want to print.
for (int i = 0; i < students; i++)
{
System.out.println("List of all Students:");
System.out.println("Firstname:"+StudentList.get(i).firstName()+" Lastname:"+StudentList.get(i).lastName());
}
}
}