I need to store user input in an array, but I am having trouble accomplishing this. Can anyone offer some advice?
import java.util.Scanner;
public class EmployeeManagement {
Scanner s = new Scanner(System.in);
Employee e = new Employee();
Employee[] arrayOfEmp = new Employee[2]; //Fields
public static int index;
public void addRecord(Employee userE, int index){ //Add method
while(index<arrayOfEmp.length){
System.out.println("Please enter Employee Id : ");
e.setEmployeeId(s.next());
System.out.println("Please enter Employee Name : ");
e.setName(s.next());
this.arrayOfEmp[index]=userE;
index++;
}
That should be because you don't append the right value in your array. You append "userE" which is a parameter, but you set values inside "e", which is another Employee instance.
Scanner s = new Scanner(System.in);
Employee[] arrayOfEmp = new Employee[2]; //Fields
public int index;
public int addRecord(int index){ //Add method
while(index<arrayOfEmp.length){
Employee e = new Employee();
System.out.println("Please enter Employee Id : ");
e.setEmployeeId(Integer.parseInt(s.nextLine()));
System.out.println("Please enter Employee Name : ");
e.setName(s.nextLine());
this.arrayOfEmp[index++]=e;
return index;
}
to invoke it please use
index = addRecord(index);
then your variable index will be updated by local index var in method.
s.next() changed to nextLine()
Since, names for example [SUBASH PRAKASH] can be with spaces you have to use nextLine().
For any other integers use nextInt()
And u should be calling using this as reference : Employee e = new Employee();
Related
I'm a beginner in programming java, I have a question which asks of me to input: the student name, id, math score, english score, and science score then calculate his total and average. So I am trying to make it into a 2d array yet I don't know how to turn string array into int. Is there a way to have one array with multiple data types(char, int, string etc)?
heres my code so far
int columns = input.nextInt();
int rows=5;
int StudentName=0;
int StudentID=1;
int math=2;
int English=3;
int Science = 4;
int i = 0;
String[][] newArray = new String[columns][rows];
for (i = 0; i<columns;i++){
System.out.println("Enter Student Name ");
newArray[i][StudentName] = input.nextLine();
System.out.println("Enter Student ID ");
newArray[i][StudentID] = input.nextLine();
System.out.println("Enter Student Math Score ");
newArray[i][math] = input.nextLine();
System.out.println("Enter Student English Score ");
newArray[i][English] = input.nextLine();
System.out.println("Enter Student Science Score ");
newArray[i][Science] = input.nextLine();
}
for(i = 0; i < columns; i++){
for(int j = 0; j < 5; j++){
System.out.println(newArray[i][j]);
}
}
}
1.Create a domain object which will be your data structure and immutable;
For an example:
public class StudentInfo implements Serializable {
private static final long serialVersionUID = 1L;
private final String StudentName;
private final int StudentID;
public StudentInfo (String StudentName, int StudentID) {
this.StudentName= StudentName;
this.StudentID= StudentID;
}
public String getStudentName() {
return StudentName;
}
//More access method.
One builder method to create the object incrementally
public class StudentInfoBuilder {
private String StudentName;
private int StudentID;
private StudentInfo() {
}
public static JobInfoBuilder newBuilder() {
return new JobInfoBuilder();
}
public JobInfoBuilder withJobName(String StudentName) {
this.StudentName = StudentName;
return this;
}
public JobInfo build() {
return new StudentInfo(StudentName, StudentID);
}
}
To be simple and clear, you could do following steps:
Create Student model with all required fileds (with required types):
public class Student {
private String id;
private String name;
private String mathScore;
private String englishScore;
private String scienceScore;
}
Define method for read all students from console:
public static Student[] readStudents(Scanner input) {
Student[] students = new Student[input.nextInt()];
for (int i = 0; i < students.length; i++) {
Student student = new Student();
students[i] = student;
System.out.println("Enter Student Name ");
student.setName(input.nextLine());
System.out.println("Enter Student ID ");
student.setId(input.nextLine());
System.out.println("Enter Student Math Score ");
student.setMathScore(input.nextLine());
System.out.println("Enter Student English Score ");
student.setEnglishScore(input.nextLine());
System.out.println("Enter Student Science Score ");
student.setScienceScore(input.nextLine());
}
return students;
}
Define method to print all students to console:
public static void print(Student[] students) {
for (int i = 0; i < students.length; i++) {
Student student = students[i];
System.out.printf("Student Name: %s", student.getName());
System.out.printf("Student ID: %s", student.getId());
System.out.printf("Student Math Score: %s", student.getMathScore());
System.out.printf("Student English Score: %s", student.getEnglishScore());
System.out.printf("Student Science Score: %s", student.getScienceScore());
System.out.println();
}
}
P.S. You could use either array or list as collection. In general: do use array if you do not plan to modify size of the collection.
You could use an array of Object. Because, in the end, anything in Java is an Object (or has an "Object sibling" - like the Integer class for primitive int values). Therefore an array of Object can be used to store the various different elements that make up a pupil.
But that is the wrong approach. You use classes and objects to model the entities your code has to deal with.
Thus create a class that represents a Student. And that class has fields such as name, id, grades. And then, in the end create a one-dimensional array of Student! That is the essence of OO programming: to create helpful abstractions, instead of coupling your data by stuffing it into arrays and remembering which index "relates" things that belong together. Instead: make that relationship explicit!
Yes you can. Below is the sample code. You can follow the same procedure and try calculating the sum and avg.
class Student{
String name;
int mark1;
int mark2;
Student(String name,int mark1,int mark2){
this.name=name;
this.mark1=mark1;
this.mark2=mark2;
}
}
public class DiffDataType {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student("Mark",90,75);
Student s2=new Student("John",74,65);
Student s3=new Student("Simon",65,86);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.name+" "+st.mark1+""+st.mark2);
}
}
}
Hope this answers your question.
Get accustomed to just a couple of other data structures and java statements:
class Student {
String name;
String id;
//int mathScore;
//int englishScore;
//int scienceScore;
int[] scores = new int[3];
}
As arrays cannot grow, use a List, implemented as ArrayList.
List<Student> students = new ArrayList<>();
while (input.hasNextLine()) {
System.out.println("Enter Student Name ");
String line = input.nextLine();
if (line.equals("end")) {
break;
}
// Create a new student:
Student student = new Student();
student.name = line;
System.out.println("Enter Student ID ");
student.id = input.nextLine();
System.out.println("Enter Student Math Score ");
String line = input.nextLine();
student.scores[0] = Integer.parseInt(line);
System.out.println("Enter Student English Score ");
line = input.nextLine();
student.scores[1] = Integer.parseInt(line);
System.out.println("Enter Student Science Score ");
line = input.nextLine();
student.scores[2] = Integer.parseInt(line);
// Add the student to the list:
students.add(student);
}
// One way to walk through the list:
for (Student student : students) {}
System.out.printf("Name %s, ID %s, Math: %d.%n",
student.name, student.id, student.scores[0]);
}
I think It's better to create Student class like in previous answers, and then store them into Map:
Map<Integer, Student> students = new HashMap<>();
for (int i = 0; i < students.length; i++) {
Student student = new Student("Mark", 90, 75);
map.put(i, student);
}
So you can iterate over the map, (using students.entrySet()) and get student by key (students.get(3))
The previous answers which stated that you should create your own Student class are correct, however I will show you a way to create an array that supports multiple types:
Make the array of type Object and instead of using primitive values (i.e, int, float, char, etc) use their wrapper classes (i.e, Integer, Float, Character)
Keep in mind that this will use much more memory.
I have a class that has private variables such as employeeName and employeeNumber and methods to set and get employeeName and employeeNumber. This class is called "EmployeesInformation". In this class I have two constructors. One that gets employee's information such as EmployeesInformation(String name, String phoneNumber){...} and another one that gets the same information but also receives two additional bits of information such as String datefired and String reasonForLeave.
Now in another class called "MenuOptionMethods" I have the addEmployee method and fireEmployee method and another method to show employees information.
I created two arrayList in this class called employee and formerEmployee.
Whenever the user adds an employee I put that employee object in the arrayList called employee. When the user fires or removes an employee I want to take all of that employee's information, remove it from arrayList employee and add it to arrayList formerEmployee. That is where I'm having problems. Can someone take a look at my code and tell me what's wrong with it?
public class menuOptionMethods {
Scanner sc = new Scanner(System.in);
private ArrayList<EmployeesInformation> employee;
private ArrayList<EmployeesInformation> formerEmployee;
public menuOptionMethods() {
employee = new ArrayList<EmployeesInformation>();
formerEmployee = new ArrayList<EmployeesInformation>();
}
public void addEmployee(String eName) {
String n = eName;
System.out.println(" Enter date hired: ");
String h = sc.next();
System.out.println(" Enter employee's duty: ");
String d = sc.next();
System.out.println(" Enter employee's phone number: ");
String pN = sc.next();
System.out.println(" Enter employee's pay per hour: ");
double pPH = sc.nextInt();
System.out
.println(" Enter any additional information about employee: ");
String l = sc.next();
EmployeesInformation e = new EmployeesInformation(n, h, d, l, pN, pPH);
employee.add(e);
}
public void fireEmployee(String eName) {
// System.out.println("Enter employee's name: ");
// String name = eName;
System.out.println("Reason for employee's leave?: ");
String reason = sc.next();
System.out.println("Enter date: ");
String dF = sc.next();
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
n = eName;
h = employee.get(i).getDateHired();
d = employee.get(i).getEmployeDuty();
pH = employee.get(i).getPhoneNumber();
pPH = employee.get(i).getEmployePay();
l = employee.get(i).getAdditionalInformation();
employee.remove(i);
}
}
EmployeesInformation fE = new EmployeesInformation(n,h,d,l,pH,pPH,reason,dF); // ERROR HAPPENS HERE
}
}
You can't remove element from list while iterating it with for loop (it will throw ConcurrentModificationException. To do that, you need to use iterator and call remove() method, e.g.:
for(Iterator<Employee> iterator = employees.iterator() ; iterator.hasNext();){
Employee current = iterator.next();
if(current.getName().equals(name)){
iterator.remove();
//Add into former employees' list
break;
}
}
This will remove from existing list.
In your for loop, you don't want to do any removing because the size of the arraylist will change, and that just creates whack that is throwing you off. Assuming every employee has a unique name, you could do something like this (note I simplified making all those new variable by just transferring that employee object from one arraylist to the other):
int index;
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
formerEmployee.add(employee[i]); //date fired and reason fired can be added later
index = i;
break;
}
}
employee.remove(i);
}
I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information
I have a Student class which has;
private String name;
private long idNumber;
and getters and setters for them.
I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.
The code I have so far is;
import java.util.Scanner;
public class StudentTest {
// Main method.
public static void main(String [] args) {
}
// Method that asks user for size of array.
public static Student[] createArray() {
System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];
return students;
}
// Method that asks user to populate array.
public static void populateArray(Student [] array) {
for(int i=0;i<array.length().i++) {
array[i] = new Student();
System.out.println("Enter student name: ");
Scanner userInputEntry = new Scanner(System.in);
array[i].setName(userInputEntry.next());
System.out.println("Enter student ID number: ");
array[i].setIDNumber(userInputEntry .nextLong());
}
}
// Method that displays contents of array.
public static void displayArray(Student[] array) {
}
}
How do I print the contents of the array back out to the user?
in class Student u can override toString():
#Override
public void toString(){
return "name: " + this.name;
}
and create a simple for loop
for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}
hope this helps a little
Override the toString method in Student class and then use https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])
use this in you display function if you don't want to override the toString method
for (int i = 0; i < array.length; i++) {
System.out.println("Student id : "+array[i].getIdNumber() + " Student name : " +array[i].getName());
}