This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}
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);
}
}
}
So the while loop is not working, even though it compiles. How do I position it correctly??
I tried a few things but they kinda worked. if someone on here can help me out that would be great
import java.util.Scanner;
//This is a Driver program to test the external Class named Student
public class StudentDriver //BEGIN Class Definition
{
//**************** Main Method*************************
public static void main (String[] args)
{Scanner scan = new Scanner(System.in);
//Data Definitions:
//Instance Data
String courseName;
int courseCredits;
String name;
String id;
String street;
String city;
String state;
String zip;
String major;
//Executable Statements:
//Initialize first Student
name = "Fred Fergel";
id = "0123";
street = "123 Main Street";
city = "Smalltown";
state = "NY";
zip = "12345";
major = "Computer Science";
//instantiate the Student object
Student student1 = new Student(name, id, street, city, state, zip, major);
//Test toString
System.out.println("Student 1\n\n" + student1.toString());
//Print a blank line
System.out.println();
//Add a course
student1.addCourse("CSC111", 4);//NOTE: DO NOT PUT A SPACE BETWEEN CSC AND 111
//Print schedule
System.out.println("Student 1's Schedule:\n\n");
student1.displaySchedule();//call method
final String FLAG = "Y";
String prompt = "Y";
while (prompt.equals("y"))
{
System.out.println("Please enter the name of the course: ");
courseName = scan.next();
System.out.println("How many credits is the course? ");
courseCredits = scan.nextInt();
student1.addCourse(courseName, courseCredits);
System.out.println("Do you wish to enter another course? y/n");
prompt = scan.next();
}
//end while
}//end main
}//end StudentDriver
Here is the student class:
import java.util.Scanner;
public class Student
{Scanner scan = new Scanner(System.in);
//Instance Data
String studentName;
String studentID;
String streetAddress;
String city;
String state;
String zipCode;
String major;
int totalCredits;
final int SIZE = 6;
final int MAX_CREDITS = 18;
String [ ] schedule = new String [SIZE];
int courseNumber = 0; //start out with no courses
//Create Constructor:
//Initializes the student data at instantiation time.
//-------------------------------------------------------
// Sets up the student's information.
//-------------------------------------------------------
public Student (String name, String id, String address, String cityName, String stateName, String zip, String area )
{
studentName = name;
studentID = id;
streetAddress = address;
city = cityName;
state = stateName;
zipCode = zip;
major = area;
}//end Student Constructor
//Method to Return student information as string:
//-------------------------------------------------------
// Returns the student information as a formatted string.
//-------------------------------------------------------
public String toString()
{
String studentInfo;
studentInfo = "Name:\t\t\t" + studentName + "\n" + "ID:\t\t\t" + studentID + "\n" + "Address:\t\t" + streetAddress
+ "\n" + "City:\t\t\t" + city + "\n" + "State:\t\t\t" + state + "\n" + "Zip Code:\t\t" + zipCode
+ "\n" + "Major:\t\t\t" + major + "\n";
return studentInfo;
}// end toString
//Method to determine if maximum allowed credits have been exceeded
//-------------------------------------------------------
// Returns true if total credits does not exceed 18.
//-------------------------------------------------------
private boolean checkCredits(int numCredits)
{
if (numCredits + totalCredits <= MAX_CREDITS) //make sure max credits not exceeded
{
return true; //return a true if still less than 18 credits
}
else
{
return false; //return a false if 18 credit limit is exceeded
}//end numCredits
}//checkCredits
//Method to add a course to the student’s schedule
//-------------------------------------------------------
// Adds a course to the array if total credits does not exceed 18.
//-------------------------------------------------------
public void addCourse(String course, int numCredits)
{
if (courseNumber < SIZE ) //make sure array is not full.
{
if (checkCredits(numCredits) == true) //if we’re under 18 credits
{
//add course
schedule [courseNumber] = course + ":\t\t" + numCredits + "\tCredits\n";
//increment number of credits
totalCredits = totalCredits + numCredits;
//increment number of courses
courseNumber = courseNumber + 1;
}
else //oops – can’t do more than 18 credits
{
System.out.println("You have exceeded the maximum allowed credits.");
}//end checkCredits
}
else //oops – can’t do more than 10 courses
{
System.out.println("You have exceeded 10 courses.");
}//end courseNumber
}//addCourse
//Method to display the schedule
//-------------------------------------------------------
// Will only print out the courses added to the array.
//-------------------------------------------------------
public void displaySchedule( )
{
for (int index = 0; index < courseNumber; index++)
{
System.out.println("Course #" + (index + 1) + " " + schedule[index] + "\n");
}//end for
}//end display schedule
}
String prompt = "Y";
while (prompt.equals("y"))
Y and y are not the same thing. You need to use .equalsIgnoreCase() instead of .equals() if you want it to ignore case.
Hi I'm very new to programming and I'm trying to write a programme in eclipse that does the following.
Create a Student class with 4 attributes: name, mark, course and phone number which are entered by the user.
Have a constructor which initialises those four attributes to the parameters passed in, and a display() method which displays the details of the Student.
Declares an empty array of 5 Student objects.
Create a Student object at the current position of the array using these variables.
Make a loop which calls the display() method of each Student in the array.
So far I've got the programme working to the point that it creates the array of 5 students and reads in the four different attributes from the user. But I can not figure out how to create a loop which calls the display method for each of the students.
This is my code so far..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
PS sorry in advance if I have posted this question wrong. Its my first post and I couldn't find a similar question else where.
Thanks in advance.
Your current code doesn't create an array of Student, nor populate it correctly (each loop overwrites the former data) .
Also, the way you were calling display was wrong :
System.out.println(Student[counter].display());
First, you want to call display on an instance of Student, not on the class.
Second, you don't have to call System.out.println, because displayalready does this work (and calling System.out.println with the void parameter, because the display method returns nothing, will get you nowhere)
Try this way :
Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)
Okay so i'm trying to make a program to display the top 2 highest scorers of 5 students only.
So sample output.
Enter your name : Spear
Enter score : 56
Enter your name : Sky
Enter score : 61
Enter your name : Spy
Enter score : 45
Enter your name : Raks
Enter score : 31
Enter your name : Felicio
Enter score : 39
Congratulations Sky!
Congratulations Spear!
I only know how to take the largest score and not the second here is what i got so far.
import java.util.Scanner;
public class Highest{
public static void main(String[]args) {
Scanner x = new Scanner(System.in);
String name = "";
int score;
int k;
int highest = 0;
num = x.nextLine();
largest = num;
for (int i = 0; i <= 5; i++) {
System.out.print("Enter name: ");
k = x.nextInt();
System.out.print("Enter score: ");
num = x.nextInt();
if (num > highest) {
highest = num;
}
}
System.out.println(largest);
}
} // how do i display the name of the highest score and the second placer?
You may want to look at sorting methods to solve such problems in the future e.g. sorting Arrays and sorting collections
For your particular case where you want to select the two max elements you can simply use two variables
int highestScore = 0;
String highestName = "";
int secondScore = 0;
String secondName = "";
and then
if (num > highestScore) {
secondScore = highestScore;
secondName = highestName;
highestScore = num;
highestName = name;
} else if (num > secondScore) {
secondScore = num;
secondName = name;
}
The code may be cleaner if you define a Student class to hold score and name.
Printing is straightforward
System.out.printnl("Congratulations " + highestName + "!");
System.out.printnl("Congratulations " + secondName + "!");
To expand on what Manos said:
You probably want to create a class for your students:
class Student {
private String name;
private int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public int getScore() {
return this.score;
}
public String getName() {
return this.name;
}
}
You can then add each student to a collection and use a Comparator to sort your students:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return Integer.compare(o1.getScore(), o2.getScore());
}
});
The resulting collection will hold a list where the highest scoreing students will be at the far end of the collection, or you can then reverse the collection so they are at the begining instead:
Collections.reverse(students);
Full example:
public static void main(String[] args) {
class Student {
private String name;
private int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public int getScore() {
return this.score;
}
public String getName() {
return this.name;
}
}
ArrayList<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
java.util.Random rand = new java.util.Random();
Student s = new Student("Student " + i, rand.nextInt());
students.add(s);
}
Collections.sort(students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return Integer.compare(o1.getScore(), o2.getScore());
}
});
Collections.reverse(students);
System.out.println("Highest scoring student: " + students.get(0).getName() + " with a score of " + students.get(0).getScore());
System.out.println("Highest scoring student: " + students.get(1).getName() + " with a score of " + students.get(1).getScore());
// List all students (Java 8 only...)
students.forEach( x -> System.out.println("Name: " + x.getName() + " with score: " + x.getScore()) );
}