Creating a testing class - java

I am extremely new to Java so forgive me if I am not asking this question correctly. I have an assignment that is asking me:
"Test your accessors and mutators in a class called Student_Testing.
First create the Student object, then set the value using your
mutator, and then print the value to the screen. Repeat for each of
the variables. Copy and paste the entire Student_Testing class."
So I currently have a Main class that is this:
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student("Joe", 123);
int id = student1.getStudentID();
String name = student1.getName();
System.out.println("ID 1: " + id);
System.out.println("Name 1: " + name);
int id2 = student2.getStudentID();
String name2 = student2.getName();
System.out.println("ID 2: " + id2);
System.out.println("Name 2: " + name2);
}
}
And I have have a class called Student which is this:
public class Student {
private String name;
private int student_id;
private double balance;
public Student() {
name = "";
student_id = 0;
balance = 0.0;
}
public Student(String input_name, int id) {
name = input_name;
student_id = id;
}
public String getName() {
return name;
}
public int getStudentID() {
return student_id;
}
public void setStudentID(int number) {
student_id = number;
}
public void deposit(double amount) {
balance = balance + amount;
}
}
I have no clue how I am supposed to make the Student_Testing class and to create the object Student. I get errors every time.
Is the Student_Testing class created just like the other classes I have? And how am I supposed to create a new object Student when I already have a Student class in a different class?
Like I said I am a complete beginner when it come to Java, so if this could be explained in the simplest terms possible that would be great! Thanks!

public class Main {
public static void main(String[] args) {
Student_Testing.test();
}
}
public class Student_Testing {
public static void test(){
Student student1 = new Student();
Student student2 = new Student("Joe", 123);
int id = student1.getStudentID();
String name = student1.getName();
System.out.println("ID 1: " + id);
System.out.println("Name 1: " + name);
int id2 = student2.getStudentID();
String name2 = student2.getName();
System.out.println("ID 2: " + id2);
System.out.println("Name 2: " + name2);
}
}
public class Student {
//student class stuff...
}
Here we created a new class called Student_Testing. In this class, we created a static method called test(). The stuff inside the test() function is exactly the same as it was in your original code.
Note the similarity between Student_Testing and your Main class?
We can now call this test method from your main function by simply doing Student_Testing.test();
Since you are still a beginner, it's important that you ask any follow up questions.
I highly encourage you to read through this and understand it thoroughly

Related

Static Method addStudents

So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];

3 subclass and 1 main class inheritance, but shows null in output in java?

I'm starting to get into coding. My formats are bad, but I wanna see first if my idea for the program works then correct it later on. This is program consists of the main class (Employee), then two subclasses that inherit from the main class (Part-Time and Full-Time employees) The code works but I encountered null in my employee's name output in this code or maybe I missed something. Any help, correction, or advice would be great! Thank you
Main Class
class Employee {
public String Name;
public void setName(String Name)
{
this.Name = Name;
}
public String getName()
{
return Name;
}
public void emp()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine();
}
}
Subclass FullTimeEmployee
class FullTimeEmployee extends Employee {
private double monthlySalary;
Scanner scan = new Scanner(System.in);
public void setMonthSalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
public double getMonthlySalary() {
return monthlySalary;
}
#Override
public void emp() {
System.out.println("Enter monthly salary: ");
monthlySalary = scan.nextDouble();
System.out.println("Name: " + getName());
System.out.println();
System.out.println("Monthly Salary: " + monthlySalary);
}
}
subclass PartTimeEmployee
public class PartTimeEmployee extends Employee {
Scanner scan = new Scanner(System.in);
private double ratePerHour;
private int hoursWorked;
private double wage;
public void setWage(double wage) {
this.wage = wage;
}
public double getWage() {
return wage;
}
#Override
public void emp() {
System.out.println("Enter rate per hour and no of hours worked separated by space: ");
ratePerHour = scan.nextDouble();
hoursWorked = scan.nextInt();
System.out.println("Name: " + getName());
wage = ratePerHour * hoursWorked;
System.out.println("Wage: " + wage);
}
}
RunEmployee
public class RunEmployee {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Employee emp1 = new Employee();
FullTimeEmployee fte = new FullTimeEmployee();
PartTimeEmployee pte = new PartTimeEmployee();
emp1.emp();
System.out.println("Press F for Full Time or P for Part Time: ");
char select = scan.nextLine().charAt(0);
if(select == 'F') {
fte.emp();
} else if (select =='P') {
pte.emp();
}
}
}
OUTPUT OF BOTH
Enter monthly salary:
500
Name: null
You only set name in the Employee parent class in the emp() method here:
public void emp() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine(); // here!
}
And yes, you give your child classes the same method and override and call it, but you never call the parent's version of the method, the super.emp() method, and so the name field never gets set.
A solution would be to call the super.emp() in your overrides, but this isn't good as it breaks the "single responsibility principle". And Employee should be responsible for Employee data and behaviors, but shouldn't be also responsible for handling a Scanner object and getting direct input from the user. Also, there are potential dangers from creating multiple Scanner objects based on System.in.
Much better, get all I/O, all use of Scanner, out of the Employee class and its children. The I/O should be in the main method (for this code) and instead, set name in the Employee constructor, and by calling the super constructor in the child classes, or by directly calling .setName(...) on any instances created.
e.g.,
class Employee {
public String name;
public Employee(String name) {
this.name = name;
}
public Employee() {
this(null);
}
public void setName(String Name) {
this.Name = Name;
}
public String getName() {
return Name;
}
// get rid of this
/*
public void emp() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Name: ");
Name = scan.nextLine();
}
*/
}
public class FullTimeEmployee extends Employee {
private double monthlySalary;
// Scanner scan = new Scanner(System.in); // *** get rid of this!
public FullTimeEmployee(String name) {
super(name);
}
public FullTimeEmployee() {
super();
}
public void setMonthSalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
public double getMonthlySalary() {
return monthlySalary;
}
/* // get rid of this!
#Override
public void emp() {
System.out.println("Enter monthly salary: ");
monthlySalary = scan.nextDouble();
System.out.println("Name: " + getName());
System.out.println();
System.out.println("Monthly Salary: " + monthlySalary);
}
*/
}
and then again, put all Scanner code in the main method.
Regarding variable public String Name;
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
Also, avoid using public fields unless absolutely necessary. Better to make this field protected, or even better yet, make it private.

Is there a way to send variables from main class to subclass using user input JAVA

So I'm working on a (supposedly) simple java application that uses console inputs from a user, to change private variables in another class. Now I can change the value of the private variables in the EmpCls class directly from the main class by manually inputting a variable into the object, e.g.
EmpCls empObject1 = new EmpCls("josh"); but how do I get something like this
EmpCls empObject1 = new EmpCls(ctName); to work? where ctName is the variable that the user inputs. here's the relevant code from the main class:
import java.util.*;
public class NewWan {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
EmpCls empObject1 = new EmpCls(ctName);
String ctName = empObject1.getName();
System.out.println("enter name: ");
ctName = console.next();
}
}
And the subclass in question:
public class EmpCls {
private String name;
private String ext;
private int yearStarted = 0;
public EmpCls()
{
}
public EmpCls(String inName)
{
this.name = inName;
}
public void setEmpDetails(String inName) //, String inExt, int inYearStarted)
{
this.name = inName;
// this.ext = inExt;
// this.yearStarted = inYearStarted;
}
public String getName()
{
return this.name;
}
public int getYearStarted()
{
return this.yearStarted;
}
public String getExt()
{
return this.ext;
}
public void displayDetails()
{
System.out.println("Name: " + name);
System.out.println("Ext: " + ext);
System.out.println("Year Started" + yearStarted);
}
}
some parts of the code are commented just to enable easier trouble shooting, other parts are part of a different problem im working on.
You just need to reorder the statements a bit and remove the one that doesn't make sense:
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
}
Hum... just to organize your code in the good way ? You use variable before getting value, and before declare it... Strange way ^^
public static void main(String[] args) {
System.out.println("enter name: ");
String ctName = console.next();
EmpCls empObject1 = new EmpCls(ctName);
System.out.println("You just enter " + empObject1.getName());
}

Objects in Linked Lists

I try to write a code which will have a basic menu with some options. These options are the following methods: AddStudent, changeName, setGrade and so on. I have created an object called Student which has a name, a grade and an age. I want to add Students in an linked list but when I use the method add it does not work. Here is my code:
import java.util.*;
class Student {
int age;
int grade;
String name;
static LinkedList ll = new LinkedList();
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public void addStudent() {
Scanner s = new Scanner(System.in);
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Scanner s = new Scanner(System.in);
p("Enter whose name you want to change");
String c = s.nextLine();
p("Enter the name that you want");
String b = s.nextLine();
}
public void setGrade(Student a) { //this method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the grade that you want");
int g = s.nextInt();
a.grade=g;
}
public void setAge(Student a) { //This method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the age that you want");
int h = s.nextInt();
a.age=h;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
}
The problem is at the method of addStudent. Is there any other ways,as well, with which I can make the same project?
Think about this logically. You have a Student class that represents a single Student. Why would a Student have a List of Student's? That makes no sense.
Wouldn't you have a program like Course or something that would hold the list of Students? That is where your List belongs. And don't use static unless you have a compelling reason (rare).
Here is a start for the Course class, that uses the Student to store student information and stores it in your LinkedList within the Course. You still need to implement the findStudent method and probably a method to print the List:
Class Course:
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList ll = new LinkedList();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
//student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
//student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
student.setAge(age);
}
public Student findStudent(){
p("Which student did you want to change? Please enter their name:");
String name = s.nextLine();
//Find student in the list - left for the author
Student student = null;
return student;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
Course course = new Course();
course.addStudent();
course.addStudent();
course.changeName();
course.setGrade();
}
}
And the modified Student class:
import java.util.*;
public class Student {
int age;
int grade;
String name;
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
public void setName(String name) {
this.name = name;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void setAge(int age) {
this.age = age;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
#Override
public String toString(){
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
}
This code is kind of messy because you include some code that shouldn't appear in Student class. For example, the addStudent method is not static and in order to call it, you need to first instantiate an instance of Student and call the method on it. However, the method is trying to ask user to input the information of a new Student instance, which is a bad design.
So, keep the Student class only do what it should do. For your case, Student only need to store its age, grade and name fields and define constructors to initialize these fields, and optional getter and setter methods to set and retrieve these fields upon your needs.
You will need a 'manager' class which manages your application. This class will keeps track of a list of students, and asks users to input information of a new student and then initialize the student instance and put it in the list. This Manager class can even manage an UI which you need to take user input or display information to the user. So, it will be this class's responsibility to provide a addStudent method.
Student class itself should know nothing about your application's logic like it may be a course selection program or something else. It only manages its own information while some manager class will take care of the application's logic.

Static Error: This class does not have a static void main method accepting String[].

My code compiles fine but when I go to run it, it gives me the error:
`Static Error: This class does not have a static void main method accepting String[]`
Here is my code:
class Employee{
private String name; //name reference field
private int idNumber; //integer variable holding employee's ID number
private String department; //holds the name of the employees department
private String position; //holds the name of the employee's position in the department
//the following is the first required constructor
//using the terms n,i,d, and p to assign values to the above fields
public Employee(String n, int i, String d, String p){
name=n;
idNumber=i;
department=d;
position=p;
}
//the following is a constructor that sets the fields blank to be filled in
public Employee(){
name="";
idNumber=0;
department="";
position="";
}
//writing appropriate accessor and mutator methods for all the fields
public void setName(String n){ name=n; }
public void setIdNumber(int i){ idNumber = i; }
public void setDepartment(String d){ department = d; }
public void setPosition(String p){ position = p; }
public String getName(){ return name; }
public int getIdNumber(){ return idNumber; }
public String getDepartment(){ return department; }
public String getPosition(){ return position; }
}
//new program creating employee objects
public class EmployeeInfo
{
public static void main(String[] args)
{
//create an Employee object
Employee employee1 = new Employee("Susan Meyers", 47899, "Accounting", "Vice President");
//test the accessor methods
System.out.println("***employee1***");
System.out.println("Name: " + employee1.getName());
System.out.println("ID number: " + employee1.getIdNumber());
System.out.println("Department: " + employee1.getDepartment());
System.out.println("Position: " + employee1.getPosition());
//create another Employee object
Employee employee2 = new Employee();
//test the mutator methods
employee2.setName("Mark Jones");
employee2.setIdNumber(39119);
employee2.setDepartment("IT");
employee2.setPosition("Programmer");
System.out.println("\n***employee2***");
System.out.println("Name: " + employee2.getName());
System.out.println("ID number: " + employee2.getIdNumber());
System.out.println("Department: " + employee2.getDepartment());
System.out.println("Position: " + employee2.getPosition());
//create another Employee object
Employee employee3 = new Employee();
//test the mutator methods
employee2.setName("Joy Rogers");
employee2.setIdNumber(81774);
employee2.setDepartment("Manufacturing");
employee2.setPosition("Engineer");
System.out.println("\n***employee3***");
System.out.println("Name: " + employee3.getName());
System.out.println("ID number: " + employee3.getIdNumber());
System.out.println("Department: " + employee3.getDepartment());
System.out.println("Position: " + employee3.getPosition());
}
}
I know I need to add the "public static void main(String[] args)" command somewhere but i'm not sure where!
Thank you for any help you can give!
You are creating two different class
Employee and EmployeeInfo
I am assuming you are trying to execute Employee class where compiler unable to find Public static void main
Firstly you should compile all '.java' file. You can do that using command line as
javac *.java
Secondly you should run class which has 'main' method. As
java EmployeeInfo

Categories

Resources