How to access hashmap object with class object as key - java

I want to make a program that updates the hashmap depending on the user input commands. How can I remove/update specific element of a hashmap by passing id variable of Student class as user input?
This is what I got so far:
class Student{
String name;
String secondname;
int id;
public Student(String name,String secondname,int id){
this.id = id;
this.name = name;
this.secondname=secondname;
}
public int getId(){
return this.id;
}
#Override
public String toString() {
return "Second Name: "+ this.secondname+ " Name: "+ this.name+ " ID: "+ this.id;
}
#Override
public boolean equals(Object o) {
if(this==o){
return true;
}
if (o==null){
return false;
}
if(getClass() != o.getClass()){
return false;
}
Student obj = (Student) o;
if (secondname == null) {
if(obj.secondname!= null){
return false;
}
}
else if(!secondname.equals(obj.secondname)){
return false;
}
if(name==null){
if(obj.name!=null){
return false;
}
}
else if(!name.equals(obj.name)){
return false;
}
if(getId()==0){
if(obj.getId()!=0){
return false;
}
}
else if (getId()!=obj.getId()){
return false;
}
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result= prime*result+id;
return result;
}
public class Main {
public static void main(String[] args) {
HashMap<Student,String> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put(myname,"A");
studentmap.put(mrx,"C");
studentmap.put(msx,"B");
while (true){
Scanner scan = new Scanner(System.in);
String x= scan.nextLine();
if (x.equals("add")){
System.out.println("Who do you want to add? ");
String y= scan.nextLine();
String [] splitted = y.split("\\s+");
studentmap.put(new Student(splitted[0],splitted[1],Integer.parseInt(splitted[2])),splitted[3]);
}
if(x.equals("remove")){
System.out.println("Who do you want to remove?");
String z= scan.nextLine();
int theid = Integer.parseint(z);
studentmap.remove(theid); // adding and printing works but this is what I have problem with
}
//if (x.equals("update")){
//String e= scan.nextLine();
//String [] splitted = e.split("\\s+");
//int theid = Integer.parseint(splited[0])
//studentmap.replace(theid,splitted[1]);
//}
if(x.equals("print")){
studenci.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " Grade: " + entry.getValue());
});
}
if (x.equals("end")){
break;
}
}
}
The way I want this program to work is to make the user type a command like "delete", then make him type ID ex."1234" and then remove a hash map object whose Key's ID is 1234.
EDIT:
My assignment roughly translated to english:
Make a program using a map which keys are Student class objects (with fields: name ,secondname, id ), and the values are grades.
Program should allow the user to add, delete, update the grade and print the students list. In case of deleting and updating look up the object by ID.

You have to "find" the key from the Map<Student,String> first, which matches the id you have. After that you can use it to remove the entry from the Map<Student,String>. The code might look like this:
Student s = null;
for(Student k: studentmap.keySet()) {
if (k.getId() == theid) {
s = k;
break;
}
}
This will find you the key in the Map. After that you can remove the entry:
if (s != null) {
studentmap.remove(s);
}

It'd make more sense to change:
HashMap<Student,String> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put(myname,"A");
studentmap.put(mrx,"C");
studentmap.put(msx,"B");
Into:
HashMap<Integer,Student> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put( yname.getId(),myname);
studentmap.put(mrx.getId(),mrx);
studentmap.put(msx.getId(),msx);
Then when someone types 'remove', followed by the Id, you can delete like you want/wrote:
studentmap.remove(theid); // remove student 'myname' if 1234

Related

how do i collect everything after a certain substring value

in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}

Java - while loop continues even when it should be done

I'm trying to write a controller which checks the input to get the right name from a "students" list, and somehow, even if I gave the right name, the loop continues.
I'm sure I missing something very obvious.
Here is the code:
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
while (!students.contains(str)){
System.out.println("Try again");
str = sc.nextLine();
}
edit:
the problem is with the class in the "student" list here's how the class and the list looks like:
// this gets filled right from a txt
List<Student> students = new ArrayList<>();
public class Student{
private String name;
private int gradeCount;
private int average;
private boolean homeWork;
...
}
and I would like to check the name data member in this class
You can't search for a String in a list of Student. You need to write your own contains() method, possibly something like this:
public boolean contains(List<Student> list, String s) {
for(Student student : list)
if(student.getName().equals(s)) return true;
return false;
}
Then you can do:
Scanner sc = new Scanner(System.in);
while (!contains(students, sc.nextLine()))
System.out.println("Try again");
This is of course assuming you have a getter for name.
Another option is for your Student to implement Comparable so that you can use various Collections methods and you can compare the Student objects to each other. An example of that would be:
public class Student implements Comparable<Student> {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int compareTo(Student s2) {
return name.compareTo(s2.getName());
}
}
You can then do the following:
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Chris"));
students.add(new Student("John"));
students.add(new Student("Frank"));
students.add(new Student("Devon"));
Student me = new Student("Chris");
students.contains(me); // true
Since you have Comparable now implemented, you can also sort the Student object by name by using Collections.sort(students).
More examples on using Comparable in Java https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
User a primer read:
import java.util.ArrayList;
import java.util.Scanner;
public class Sandbox {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Boolean found = false;
String input;
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("Jim"));
students.add(new Student("Kim"));
students.add(new Student("Bill"));
students.add(new Student("Betty"));
System.out.println("Enter the name of a student to check");
input = keyboard.nextLine();
if(students.get(0).getName().equals(input)) {
System.out.println("You found " + students.get(0).getName());
found = true;
keyboard.close();
}
while(!found) {
System.out.println("Try again");
input = keyboard.nextLine();
for(int i = 1; i < students.size(); i++) {
if(students.get(i).getName().equals(input)) {
System.out.println("You found " + students.get(i).getName());
found = true;
keyboard.close();
break;
}
}
}
}
Student class
public class Student {
String name;
public Student () {
}
public Student (String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
Assuming there's a getter for the Student object, you can map the list of Student objects to a list of students names (String) and then perform the .contains() call on that list. So try this:
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// Create a List<String> of student names
List<String> names = students
.stream()
.map(student -> student.getName())
.collect(Collectors.toList());
while (!names.getName().contains(str)){
System.out.println("Try again");
str = sc.nextLine();
}
Scanner sc = new Scanner(System.in);
String str=null;
boolean isFound=false;
while (!isFound)
{
str = sc.nextLine();
for(Student stdObj:students)
if(stdobj.name.equals(str))
{
isFound=true;
break;
}
if(!isFound)
System.out.println("Try again");
}

I don't know where my String index out of range: 0 error is coming from

I'm trying to take data out of a txt file and create comparable objects out of the data and add them to an array. After that array is created, I want to make a 2d array that stores a 1 in a slot if two options meet the requirements. I keep getting a String index out of range: 0 error though and I do not know where it comes from.
import java.util.*;
import java.io.*;
public class CourseScheduler
{
public int numberOfCourses;
public int[][] adjacent;
public Course[] courses;
public CourseScheduler(String filename)
{
File file = new File(filename);
try{
Scanner scan = new Scanner(file);
numberOfCourses = scan.nextInt();
courses = new Course[numberOfCourses];
adjacent = new int[numberOfCourses][numberOfCourses];
scan.useDelimiter(",|\\n");
for(int i = 0; i < numberOfCourses;i ++){
if(scan.hasNext()){
String dept = scan.next();
String num = scan.next();
String building = scan.next();
String room = scan.next();
String instruct = scan.next();
courses[i] = new Course(dept, num, building, room, instruct);
}
}
}
catch(FileNotFoundException ex){
System.out.println("File was not found");
}
for(int x = 0;x<numberOfCourses;x++){
for(int y = 0;y<numberOfCourses;y++){
adjacent[x][y] = (courses[x].compare(courses[y]));
}
}
}
This is the code for the main class
public class Course{
String department;
String courseNum;
String buildingCode;
String roomCode;
String instructorName;
public Course(String dept, String number, String building, String room, String instructor){
department = dept;
courseNum = number;
buildingCode = building;
roomCode = room;
instructorName = instructor;
}
public String getDept(){
return department;
}
public String getCourse(){
return courseNum;
}
public String getBuilding(){
return buildingCode;
}
public String getRoom(){
return roomCode;
}
public String getInstructor(){
return instructorName;
}
public String toString(){
return department + ";" + courseNum + ";" + buildingCode + ";" + roomCode + ";" + instructorName;
}
public int compare(Course comp){
int ans = 1;
String compNum = comp.getCourse();
if(instructorName == comp.getInstructor())
ans = 0;
if(buildingCode == comp.getBuilding()){
if(roomCode == comp.getRoom())
ans = 0;
}
if(department == comp.getDept()){
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
}
return ans;
}
}
this is the code for the course class
Educated guess: Most likely your error is coming from this line:
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
Either courseNum or compNum are empty.
I did not try to compile and run it but its seems that the exception comes from this line
if(courseNum.charAt(0) == compNum.charAt(0))
If a string is empty, charAt(0) will throw exactly the given exception.
Tip: if you don't know how to use a debugger, use the old fashioned System.out.println(). Put println() here and there in your code to understand how it works.

Removing item from ArrayList using remove(<index>) or remove(<objectRef>)

I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.

Storing an object in array

My code is supposed to read a sequence until the empty line. I am stuck at storing the object in array at numItem and then increase numItem.
public static int readInput(Scanner myScanner, String[] input) {
boolean streamEnded = false;
int numItem = 0;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
} else {
input[numItem] = name;
input[numItem] = id;
numItem++;
}
Person personTest = new Person(name, id);
persons[numItem]
}
return numItem;
}
}
A few things:
Put the numItem increment outside of the if/else statement. It should go at the end of your while loop after persons[numItem].
Not sure what this: persons[numItem] is supposed to do. If you mean to store the personTest object at that index it should be persons[numItem] = personTest;.
Unless you know you are only going to have 10 people created in your array, I would use an ArrayList, that way you could add as many Person objects as you need.
I didn't go through it line by line, those are just my general observations. I'm pretty sure your code won't compile as it is, especially with this: persons[numItem]. Hope this helps a bit.
I think you are looking for something like this,
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
List<Person> persons = new ArrayList<Person>();
while (myScanner.hasNext()) {
String inp = myScanner.nextLine();
if (inp.length() <= 0) {
break;
}
String[] parts = inp.split(" ");
persons.add(new Person(parts[0], parts[1]));
}
while (myScanner.hasNext()) {
String inp = myScanner.nextLine();
if (inp.length() <= 0) {
break;
}
String[] parts = inp.split(" ");
Person person = findPerson(persons, parts[0]);
person.changeBalance(Double.parseDouble(parts[1]));
System.out.println(person);
}
}
private static Person findPerson(List<Person> persons, String id) {
for (Person person : persons) {
if (person.getId().equals(id)) {
return person;
}
}
return new Person("", "");
}
Here I have used a ArrayList instead of array to make things easier. I have printed the person every time the balance changes. But, you can move it outside of the loop to match your output.

Categories

Resources