I am doing some coding in Java, but it doesn't work:
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String [] studentId = new String [3];
Student name;
for (int i = 0; i < 3; i++)
{
System.out.print("Enter Name => ");
name = new Student(input.next());
studentId[i] = name.toString();
}
for (int i = 0; i < 3; i++)
{
System.out.println(studentId[i]);
}
}
}
public class Student
{
private static int studentId;
private String name;
public Student(String name)
{
this.name=name;
setStudentId(studentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
#Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
I need to auto-increment the Id when a new entry is created.
I try everything but still cant increased it.
You are using a static variable for everyone's Ids. You need a separate, non-static field to store each individual Id.
public class Student
{
private static int nextAvailableStudentId = 1;
private String name;
private int studentId;
public Student(String name)
{
this.name=name;
setStudentId(nextAvailableStudentId++);
}
public int getStudentId()
{
return studentId;
}
public void setStudentId(int studentId)
{
this.studentId = studentId;
}
#Override
public String toString()
{
return (this.studentId +" "+ "student is "+ " " + "(" + this.studentId + ")"+ this.name);
}
}
In constructor it should be:
{
public Student(String name)
{
this.name=name;
setStudentId(studentId + 1);
}
}
Related
Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```
constructor Student in class javaapplication 14.Student cannot be
applied to given types; required:
java.lang.String,int,java.lang.String,java.lang.String,double found:
java.lang.String,double reason: actual and formal argument lists
differ in length
This is the line that gives me error
super(idNum, gpa);
here is my code:
package javaapplication14;
public class JavaApplication14
{
public static void main(String[] args)
{
Person bob = new Person("Coach Bob", 27, "M");
System.out.println(bob);
Student lynne = new Student("Lynne Brooke", 16, "F", "HS95129", 3.5);
System.out.println(lynne);
Teacher mrJava = new Teacher("Duke Java",34,"M","Computer Science",50000);
System.out.println(mrJava);
}
}
class Person
{
protected String myName ;
protected int myAge;
protected String myGender;
public Person(String name, int age, String gender)
{
myName = name;
myAge = age ;
myGender = gender;
}
#Override
public String toString()
{
return myName + ", age: " + myAge + ", gender: " +myGender;
}
//These are the set methods
void setName(String name)
{
myName = name;
}
void setAge(int age)
{
myAge = age ;
}
void setGender(String gender)
{
myGender = gender;
}
//These are the get methods
String myName()
{
return myName;
}
int myAge()
{
return myAge;
}
String myGender()
{
return myGender;
}
}
class Student extends Person
{
protected String myIdNum;
protected double myGPA;
public Student(String name, int age, String gender,String idNum, double gpa)
{
super(name, age, gender);
myIdNum = idNum;
myGPA = gpa;
}
//These are the set methods
void setmyIdNum(String idNum)
{
myIdNum = idNum;
}
void setmyGPA(double gpa)
{
myGPA = gpa;
}
#Override
public String toString()
{
return super.toString() + ", student id: " + myIdNum + ", gpa: " + myGPA;
}
public String myIdNum()
{
return myIdNum;
}
double myGPA()
{
return myGPA;
}
}
class Teacher extends Person
{
public double mySalary;
public String mysubjectName;
public Teacher( String name, int age, String gender, String
subjectName,double salary )
{
super(name, age, gender);
mysubjectName = subjectName;
mySalary = salary;
}
//These are the setter methods
void setsubjectname(String subjectName)
{
mysubjectName = subjectName;
}
void setsalary(double Salary)
{
mySalary = Salary;
}
#Override
public String toString()
{
return super.toString() + ", subject name: " + mysubjectName + ", Salary: "
+ mySalary;
}
//These are the getter methods
public String getsubjectname(String subjectName)
{
return subjectName;
}
double getsalary(double Salary)
{
return Salary ;
}
class CollegeStudent extends Student
{
public String myMajor;
public int myYear;
public CollegeStudent(String name, int age,String gender,
String idNum, double gpa, int year, String major )
{
super(idNum, gpa);
myMajor = major;
myYear = year;
}
void setmajor(String Major)
{
myMajor = Major;
}
void setyear(int Year)
{
myYear = Year;
}
#Override
public String toString()
{
return super.toString() + ", major: " + myMajor + ", Year: " + myYear;
}
//These are the getter methods
public String getmajor(String myMajor)
{
return myMajor;
}
public int getyear(int myYear)
{
return myYear ;
}
}
}
There is no such constructor with two parameters in Student class
The class Student and also the class Person has no constuctor with the signature (String, double).
So you have to create this constructor in one of the superclasses or you have to call an other constructor.
Your super class Student has following constructor with 5 parameter
public Student(String name, int age, String gender,String idNum, double gpa)
But, at CollegeStudent constructor, super(idNum, gpa); expect a constructor with two parameter Student(String idNum, double gpa), which is missing in superclass. So, define a constructor at Student class like:
class Student extends Person {
public Student(String idNum, double gpa){
}
}
Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?
What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));
i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}