HashMap for Student Object does not print objects of Student - object

import java.util.Scanner;
public class StudentMap extends Student{
public static void main(String[] args)
{
Student[] studentClass = new Student[2];
Scanner s1 = new Scanner(System.in);
for(int i=1;i<=studentClass.length;i++)
{
System.out.println("Enter name for "+i+"Student");
String studentName = s1.next();
System.out.println("Enter email for "+i+"Student");
String email = s1.next();
System.out.println("Enter phone number for "+i+"Student");
Integer num = s1.nextInt();
studentClass[i] = new Student();
studentClass[i].setName(studentName);
studentClass[i].setEmail(email);
studentClass[i].setPhoneNumber(num);
}
s1.close();
for(Student stu : studentClass)
{
System.out.println(stu.name);
System.out.println(stu.email);
System.out.println(stu.phoneNumber);
}
}
}
While executing this code it gives an error of OutOfBoundIndex ..
I have created Student class to which has all get set method for name, email and phoneNumber.

Related

Using a string to specify an object in Java

I have a Combo Bx (Dropdown box) with an index range of 0-20. If there anyways I can use that index to specify which object I want data from? All of the objects use the same naming convention obj0, obj1, obj2, etc. Basically something like this...
public abstract class Person {
private String name;
private String title;
private String email;
private String job;
public Person(String name, String title, String email, String job){
this.name = name;
this.title = title;
this.email = email;
this.job = job;
}
//Getters and Setters
}
public class main extends javax.swing.JFrame {
...misc code...
private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {
Person obj0 = new Person("Jon Doe",
"Program Coordinator",
"jon.doe#test.com",
"Faculty");
Person obj1 = ...
...
Person obj20 = ...
/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {
//Uses the obj naming convention plus the index
string foo = "obj" + toString(combobox_Name.getSelectedIndex());
//Fills the textbox using the above string and the getName method
txtbox_username.setText(ToObject(foo).getName);
}
I have created a basic design of what I think you want:
This code creates 20 objects, adds them to a combobox and uses their predefined name when selected to change a textfield.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class ObjExample {
String name;
public ObjExample(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
public class Main extends JFrame implements ActionListener {
JComboBox jcb = new JComboBox();
JTextField jtf = new JTextField("Text Field");
public Main() {
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i = 0; i <= 20; i++) {
jcb.addItem(new ObjExample(Integer.toString(i)));
}
jcb.addActionListener(this);
add(jcb);
add(jtf);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jcb) {
ObjExample obj = (ObjExample) jcb.getSelectedItem();
jtf.setText(obj.toString());
}
}
}

C#: how to display the employee names with lowest salary

I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information.
i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.
here is the class employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
My question is:
How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?
You need to make your class Employee to implement the IComparable interface, then compare the objects against the salary and in the other class sort the array...
Example:
public class Employee :IComparable<Employee>
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public int CompareTo(Employee other)
{
return salary.CompareTo(other.salary);
}
}
private void Find()
{
Array.Sort(employee); // after this Employee is sorted
employee[0];
or
employee[9];
}
this will give a list of lowest salary emplyees
employee.Add(new Employee(17434, "Stephen", "Rad", 9000.00));
employee.Add(new Employee(17435, "Jesse", "Harris", 800.00));
employee.Add(new Employee(17436, "jonatan", "Morris", 9500.00));
var c = employee.OrderBy(i => i.salary).ToList();
var e = employee.Where(i => Math.Abs(i.salary - c[0].salary) < 1).ToList();
Modified you code a little bit
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
//public Employee()
//{
// employeeID = 0;
// fullName = "";
// lastName = "";
// salary = 0.0;
//}
//public Employee(int empIDValue, string fullNameVal, string lastNameVal)
//{
// employeeID = empIDValue;
// fullName = fullNameVal;
// lastName = lastNameVal;
// salary = 0.0;
//}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
and to get min values in list
var minEmpSalarylist = employee.Where(x => x.Salary == employee.Min(y => y.Salary)).ToList();
If default constructor is present then all minEmpSalarylist become initialized with default constructor.
and
employee[0] = new Employee();
to change it to
employee[0] = new Employee(17433, "XXX", "YYY", 8000.00);

Using a user input to make an object in Java

Is there a way for me to take a string input from scanner and create a new object with that string entry? Such as:
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
ListOfNames name = new ListOfNames();
}
Note that in the last line the "ListOfNames name = new ListOfNames();" I want the new object to be the string that the variable "name" holds.
I want to do this so that after the object is made I can add it to an array then be able to search the array later after inputting multiple names in for the one I need.
There is probably a way to do this with the arrays class but I am new and unfimliar with the class. Any help would be fantastic! Thanks!
You could do...
public class Test {
public static void main(String[] args) {
ArrayList<String> listOfNames = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
listOfNames.add(name);
}
Just add the received input from Scanner to listOfNames array list.
Or if you are really need to use another Object...
public class Name {
String value;
public Name(String value) {
this.value = value;
}
}
public class Test {
public static void main(String[] args) {
ArrayList<Name> listOfNames = new ArrayList<Name>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String nameValue = input.nextLine();
Name n = new Name(nameValue);
listOfNames.add(n);
}

Get property values from a string using Reflection

I am new to this concept of reflection and finding problem in retrieving property value from a string. E.g.
I have a class Employee with following properties :
public string Name {get;set;}
public int Age {get;set;}
public string EmployeeID {get;set;}
string s = "Name=ABCD;Age=25;EmployeeID=A12";
I want to retrieve the value of each property from this string and create a new object of Employee with those values retrieved from the string for each field.
Can anyone please suggest how it can be done using reflection ??
//may be..
string s = "Name=ABCD;Age=25;EmployeeID=A12";
string[] words = s.Split(';');
foreach (string word in words)
{
string[] data = word.Split('=');
string _data = data[1];
Console.WriteLine(Name);
}
Here an example of how you maybe could do it
it used Reflection like you wanted ^^
using System;
using System.Collections.Generic;
using System.Reflection;
namespace replace
{
public class Program
{
private static void Main(string[] args)
{
var s = "Name=ABCD;Age=25;EmployeeID=A12";
var list = s.Split(';');
var dic = new Dictionary<string, object>();
foreach (var item in list)
{
var probVal = item.Split('=');
dic.Add(probVal[0], probVal[1]);
}
var obj = new MyClass();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(dic[property.Name]);
if (property.PropertyType == typeof(Int32))
property.SetValue(obj, Convert.ToInt32(dic[property.Name]));
//else if (property.PropertyType== typeof(yourtype))
// property.SetValue(obj, (yourtype)dic[property.Name]);
else
property.SetValue(obj, dic[property.Name]);
}
Console.WriteLine("------------");
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Age);
Console.WriteLine(obj.EmployeeID);
Console.Read();
}
}
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
public string EmployeeID { get; set; }
}
}

HashMap<String, Student> searching for instance in Student class

I am working with two helper classes (Student, Helper), as well as a main class.
In the Student class, I have the following constructor:
Student(String iName, String iMajor, int iNumber) {
name = iName;
major = iMajor;
number = iNumber;
}
In the Helper class, I declare a HashMap as follows:
HashMap<String, Student> students = new HashMap<String, Student>();
Now, I have written a few method for adding (put) new students into the HashMap construction, as well as a method for retrieving information about a student based on the name.
//Adding new students
Student s1 = new Student("Alex", "Biology", 19);
Student s2 = new Student("Brian", "Chemistry", 20);
Student s3 = new Student("Tom", "Biology", 20);
//etc...
//Get student from name (key)
public Student getFromKey(String key) {
return students.get(key);
}
I am now looking to write a method that finds all students based on either major or number. For instance, the call:
helper.getStudents("Biology");
Should return all the students studying Biology. I imagine the method looking something like:
public Student getStudents(String searchItem) {
for(Students st : students.values()) {
if(searchItem.equals(??)) {
return st;
//Something like this.
However, I can't seem to figure out how to access these values. All the classes have appropriate getter and setter methods, and the program works fine. Any help is highly appreciated!
Assuming this Map exists:
HashMap<String, Student> students = new HashMap<String, Student>();
The following would work:
public Student getStudents(String searchItem) {
for(Map.Entry<String,Student> entry : students.entrySet()) {
Student student = entry.getValue();
//perform conditional logic here
}
Here is a more complete example in case you need it:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Student {
private String name;
private String major;
private int number;
public Student(String name, String major, int number) {
super();
this.name = name;
this.major = major;
this.number = number;
}
public static void main(String[] args) {
List<String> names = Arrays.asList("Joe", "Jack", "John","James");
List<String> majors = Arrays.asList("English","Math","Geography");
Map<String,Student> students = new HashMap<String,Student>();
for(int i = 0; i < 100; i++){
Collections.shuffle(names);
Collections.shuffle(majors);
students.put(names.get(0) + String.valueOf(i), new Student(names.get(0), majors.get(0), i));
}
List<Student> mathMajors = getStudents(students, "Math");
for(Student student:mathMajors){
System.out.println(student.name);
System.out.println(student.major);
}
}
public static List<Student> getStudents(Map<String,Student> students, String searchToken){
List<Student> results = new ArrayList<Student>();
for(Entry<String,Student> entry:students.entrySet()){
if(entry.getValue().getMajor().equalsIgnoreCase(searchToken)){
results.add(entry.getValue());
}
}
return results;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMajor() {
return this.major;
}
public void setMajor(String major) {
this.major = major;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
}
On Github

Resources