Background
Building an Assembler in Java:
I'm trying to read user's input into an ArrayList named v.
If the user enters an instruction that matches one of the String-array table, then the corresponding opcode will be calculated and output into a textfile.
Problem
However, after inputting the nop instruction and trying to add another instruction, I got an index out of bounds exception.
Source Code
//Array of instructions
String table[] = {"LI", " MALSI", "MAHSI", "MSLSI", "MSHSI", "MALSL", "MAHSL",
"MSLSL", "MSHSL", "NOP", "A", "AH", "AHS", "AND", "BCW", "CLZ", "MAX", "MIN",
"MSGN", "MPYU", "OR", "POPCNTH", "ROT", "ROTW", "SHLHI", "SFH", "SFW", "SFHS", "XOR "};
//Array of binary values of the instructions
String table2[] = {"0", "10000", "10001", "10010", "10011", "10100", "10101",
"10110", "10111", "1100000000000000000000000", "1100000001", "1100000010", "1100000011",
"1100000100", "1100000101", "1100000110", "1100000111", "1100001000", "1100001001",
"1100001010", "1100001011", "1100001100", "1100001101", "1100001110", "1100001111",
"1100010000", "1100010001", "1100010010", "1100010011"};
// TODO code application logic here
Scanner s = new Scanner(System.in);
String ins = "";
String fileName = "outfile.txt";
System.out.println("Please enter MISP function, enter Q to Quit: ");
boolean q = true;
String op = "";
int c = 0;
String array[] = new String[64];
//Loop to keep accepting userinput
while (q) {
//accepts the user input
ins = s.nextLine();
//arraylist to hold user input
List<String> v = new ArrayList<String>();
//adds the user input to the arraylist
v.add(ins);//user input to nop opcode
if (v.get(0).toUpperCase().equals("NOP")) {
op = "1100000000000000000000000";
} else if (v.get(1).toUpperCase().equals("LI"))//li opcode
{
String p[] = v[1].split(",", 1);
op = "0";
op += toBinary(p[0], 3);
op += toBinary(p[1], 16);
op += toBinary(p[2], 5);
Error Stacktrace I got
Exception in thread "main" java.lang.IndexOutOfBoundsException:
If you guys could help it would be appreciated.
This loop will never end.
while (q)
Related
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The overall project is creating a system manager for airports. It keeps track of airports, flights, seating sections, seats and other relevent info for each of those catagories. The initial system is set up by importing from a file that's formatted a certain way. I'm having problems parsing the file properly to set up the initial system. the data is parsed from the file and used as method parameters to create the objects: Airport, Airline, Flight, FlightSection, and Seat.
the formatting is:
[list-of-airport-codes] {list-of-airlines}
list-of-airport-codes ::= comma-separated strings
list-of-airlines ::= airline-name1[flightinfo-list1], airline-name2[flightinfo-list2], airlinename3[flightinfo-list3], …
flightinfo-list ::= flightID1|flightdate1|originAirportCode1|destinationAirportCode1[flightsectionlist1], flightID2|flightdate2|originAirportCode2|destinationAirportCode2[flightsection-list2], …
flightdate ::= year, month, day-of-month, hours, minutes
flightsection-list ::= sectionclass: seat-price: layout: number-of-rows, …
sectionclass ::= F, B, E (for first class, business class, economy class)
layout ::= S, M, W (different known seating layouts)
example:
[DEN,NYC,SEA,LAX]{AMER[AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],
AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3], …], UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3], UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2], …], FRONT[…], USAIR[…]}
I tried brute forcing it using a combination of delimiters and while loops. The code successfully creates the Airports, first Airline and Flighsections, but when it gets to creating the second airline it crashes, because i'm not looping properly, and having a hard time getting it right. My code for it as of now, is a mess, and if you're willing to look at it, I would appreciate any constructive input. My question is what would be a better way to approach this? A different design approach? Maybe a smarter way to use the delimiters?
Thanks in advance for your help!!
here's what i've tried.
private void readFile(File file){
System.out.println("reading file");
Scanner tempScan;
String result;
String temp = "";
scan.useDelimiter("\\[|\\{");
try{
// AIRPORTS
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|\\]");
while(tempScan.hasNext()){
temp = tempScan.next();
sysMan.createAirport(temp);
}
tempScan.close();
/* AIRLINE
* FLIGHT
* FLIGHTSECTION
*/
do{
// AIRLINE (loop<flight & fsection>)
result = scan.next();
sysMan.createAirline(result);
// FLIGHT
result = scan.next();
tempScan = new Scanner(result);
do{
tempScan.useDelimiter(",|\\|");
ArrayList flightInfo = new ArrayList();
while(tempScan.hasNext()){
if(tempScan.hasNextInt()){
flightInfo.add(tempScan.nextInt());
} else {
flightInfo.add(tempScan.next());
}
}
tempScan.close();
sysMan.createFlight(sysMan.getLastAddedAirline(),(String)flightInfo.get(0), (int)flightInfo.get(1), (int)flightInfo.get(2), (int)flightInfo.get(3), (int)flightInfo.get(4), (int)flightInfo.get(5), (String)flightInfo.get(6), (String)flightInfo.get(7));
// FLIGHTSECTION (loop<itself>)
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|:|\\]");
ArrayList sectInfo = new ArrayList();
int i = 1;
while(!temp.contains("|")){
if(tempScan.hasNextInt()){
sectInfo.add(tempScan.nextInt());
} else {
temp = tempScan.next();
if(temp.equals(""))
break;
char c = temp.charAt(0);
sectInfo.add(c);
}
if(i == 4){
sysMan.createSection(sysMan.getLastAddedAirline(), sysMan.getLastAddedFlightID(), (char)sectInfo.get(0), (int)sectInfo.get(1), (char)sectInfo.get(2), (int)sectInfo.get(3));
i = 1;
sectInfo = null;
sectInfo = new ArrayList();
continue;
}
i++;
}
}while(!temp.equals("\\s+"));
}while(!temp.contains("\\s+"));
}catch(NullPointerException e){
System.err.println(e);
}
}
I'd rather chunk it down by regexp mathing the outer bounds, have a look, I took it a couple of levels broken.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokeni {
static String yolo = "[DEN,NYC,SEA,LAX]{AMER["
+ "AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],"
+ "AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3]],"
+ "UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3],"
+ "UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2]]}";
public static void main(String[] args) {
Matcher airportCodesMatcher = Pattern.compile("\\[(.*?)\\]").matcher(yolo);
airportCodesMatcher.find();
String[] airportCodes = airportCodesMatcher.group(1).split(",");
Matcher airLinesMatcher = Pattern.compile("\\{(.*?)\\}").matcher(yolo);
airLinesMatcher.find();
String airLinesStr = airLinesMatcher.group(1);
System.out.println(airLinesStr);
Pattern airLinePattern = Pattern.compile("\\D+\\[(.*?)\\]\\]");
Matcher airLineMatcher = airLinePattern.matcher(airLinesStr);
while( airLineMatcher.find() ) {
String airLineStr = airLineMatcher.group(0).trim();
if(airLineStr.startsWith(",")) {
airLineStr = airLineStr.substring(1, airLineStr.length()).trim();
}
System.out.println(airLineStr);
Matcher airLineNameMatcher = Pattern.compile("[A-Z]+").matcher(airLineStr);
airLineNameMatcher.find();
String airLineName = airLineNameMatcher.group(0).trim();
System.out.println(airLineName);
airLineStr = airLineStr.substring(airLineStr.indexOf("[")+1, airLineStr.length());
Matcher airLineInfoMatcher = Pattern.compile("\\D+(.*?)\\]").matcher(airLineStr);
while(airLineInfoMatcher.find()) {
String airLineInfoStr = airLineInfoMatcher.group(0).trim();
if(airLineInfoStr.startsWith(",")) {
airLineInfoStr = airLineInfoStr.substring(1, airLineInfoStr.length()).trim();
}
System.out.println(airLineInfoStr);
}
}
}
}
The exercise is, to create an arraylist for a class, where a User can enter "Guestnumber" + "Guestname" + "Guestemail".
In the menu you could remove an existing "Guest" with all the Information. Thats the code for it: (it works)
public void gastAendern() {
System.out.println("Guestnumber to delete:");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
verwaltungG.remove(test);
a = 1;
break;
}
}
if(a==0) {
System.out.println("Guestnumber is not used");
verwaltungG is the ArrayList
Gast is the class for get+set
But now I got a problem to change an existing Guest, like for example:
I ask to type in the Guestnumber OR the Guestname OR the Guestmail to change it (I have to do it for all 3). So I have really no idea how to change it. I looked through Stackoverflow, google etc. but it only shows how to change them with List.set, but I don't know if it works with my kind of Problem, because I don't know how to use it.
You can do something similar as you are doing for delete, instead of remove - you need to change the details you need update :
System.out.println("Guestnumber to update :");
Scanner sc = new Scanner(System.in);
String input = sc.next();
for (Gast test : verwaltungG) {
int nummer = Integer.parseInt(input);
if (test.getgNr() == nummer) {
System.out.println("Enter new guest name for guest number : "+nummer );
String name = sc.nextLine();
System.out.println("Enter new guest email for guest number : "+nummer );
String email = sc.nextLine();
// now update the details
test.setName(name);
test.setEmail(email);
break;
}
}
How can I search element in arraylist and display it? Example is the user wants to search the code A25 Then it will print the whole content on that arraylist that he search only and the output is A25 CS 212 Data Structures 3.
Subject CS212 = new Subject("A25","\t\tCS 212","\t\tData Structures\t\t\t\t",units);
Subject IT312 = new Subject("A26","\t\tIT 312","\t\tData Base Management System 2\t\t",units);
Subject IT313 = new Subject("A27","\t\tIT 312","\t\tData Base Management System 2\t\t",units);
Subject CS313 = new Subject("A29","\t\tCS 313","\t\tDigital Designt\t\t\t\t",units);
Subject Disc = new Subject("A30","\t\tIT 212","\t\tDiscrete Structurest\t\t",units);
Subject A31 = new Subject("A31","\t\tIT 212","\t\tDiscrete Structurest\t\t",units);
Subject Engl3 = new Subject("984","\t\tEngl 3","\t\tSpeech and oral Communicationt\t\t",units);
Subject Theo3 = new Subject("582","\t\tTheo 3","\t\tChrist and Sacramentst\t\t",units);
Subject Stat = new Subject("470","\t\tStata1","\t\tProbablility and Statisticst\t\t",units);
Subject Dota = new Subject("999","\t\tDota 2","\t\tDota Guide\t\t\t\t",units);
ArrayList<Subject> arrList = new ArrayList<Subject>();
arrList.add(CS212);
arrList.add(IT312);
arrList.add(IT313);
arrList.add(CS313);
arrList.add(Disc);
arrList.add(A31);
arrList.add(Engl3);
arrList.add(Theo3);
arrList.add(Stat);
arrList.add(Dota);
//User input that he wants to search
for(int i = 0; i < 3; i++,num++)
{
System.out.print("\t\t"+num +". ");
codeNo[i] = scan.next();
String output = Character.toUpperCase(codeNo[i].charAt(0)) + codeNo[i].substring(1);
codeNo[i] = output;
}
// This is what I tried but it doesn't work Idk why
for (Subject s : arrList) {
for(int i =0; i < codeNo.length; i++)
if (s.equals(codeNo[i])) {
System.out.println("\t\t\t"+s);
}
}
public Subject(String codeNo, String subjectID, String title , int unit)
{
//Constructor . .
}
//Desired output
Code to search
A25
A26
A27
output
A25 CS 212 Data Structures 3
A26 IT 312 Data Base Management System 2 3
A27 IT 312 Data Base Management System 2 3
You are trying to search an arraylist of subjects, you need to write a small function to compare the code string to the corresponding string of the class. You can do this by adding this to your subject class.
Example :
#Override
public boolean equals(String code) {
return code.equals(this.<compare to member>);
}
and change the compare to member that needs to match the code that you match.
EDIT : Easier way to do is to just change your existing code to :
if (s.code.equals(codeNo[i])) //assuming your code class member is a public string
Search by id method:
public class ClientsDetailsList {
public ArrayList <ClientDetails> aListOfClientDetails;
public ClientDetails getClientDetails(String givenID) {
boolean found = false;
int index = 0;
for(;index<aListOfClientDetails.size();index++){
if((aListOfClientDetails.get(index).ClientID.equals(givenID)))
found = true;
}
if(found)
return aListOfClientDetails.get(index);
else return null;
}
}
aListOfClientDetails List format It reads a file and creates a list of ClientDetails.
[IC-x00042W Ms LQ Bethea 205, Willis Road Bolton BO5 1DQ 2000000007 2000100037 2006200319,
IC-x00033D Mr R Bowie 119, Thatcher Way Glasgow GL9 5SX 2006000016 2003100008 2005300001,
IC-x00013A MS GRV Blackwell 209, Drunk Road Hawick HK8 1MY 2006000009 2004100014 2003200304,
IC-x00018O Ms NAP Wallis 244, Grubb Lane Durham DU4 4ZX 2000000006 2003100012 2006200305]
One line is an object of the list. With the method above I try to return an object of the list found by ID (e.g. first token IC-x00042W). However when I run this in my main method it returns Only the first object.(IC-x00042W/Ms/LQ/Bethea/205, Willis Road/Bolton/BO5.....)
If I search by id of another object it returns null.
Source of ClientDetailsList:
The txt file has the following data:
IC-x00042W/Ms/LQ/Bethea/205, Willis Road/Bolton/BO5 1DQ/2000000007/2000100037/2006200319#
IC-x00033D/Mr/R/Bowie/119, Thatcher Way/Glasgow/GL9 5SX/2006000016/2003100008/2005300001#
IC-x00013A/MS/GRV/Blackwell/209, Drunk Road/Hawick/HK8 1MY/2006000009/2004100014/2003200304#
IC-x00018O/Ms/NAP/Wallis/244, Grubb Lane/Durham/DU4 4ZX/2000000006/2003100012/2006200305#
IC-x00037N/Miss/DOD/Burke/272, Ambrose Lane/Cambridge/CB2 2XD/2005000003/2001100020#
IC-x00039A/Dr/X/Salter/285, Bannister Road/Sea Palling/SP2 6GW/2000000002/2005100029/2005200306#
IC-x00011I/MR/R/Reece/104, Bannister Lane/Cromer/CR0 6LD/2005000012/2003100001/2001200300#
IC-x00025V/Mr/P/Abbott/163, Drunk Lane/Hunstanton/HU1 1UR/2003000029/2004100017#
IC-x00008L/Dr/P/Runyon/150, Tick Tock Way/Swindon/SW8 4OJ/2004000005/2006100005/2001200316#
IC-x00028F/MR/X/Watt/267, Malton Road/Cambridge/CB4 1PQ/2004100016/2004200312#
IC-x00031X/Mr/S/Lorenz/276, Tick Tock Way/London/LN9 7ID/2005000023/2005100007#
IC-x00020C/Mr/LNV/Mcmillan/44, Drunk Street/London/LN6 1RG/2001000019#
IC-x00015H/Mr/TQZ/Dubose/201, Drunk Road/London/LN4 5RA/2003000026/2006100028/2000200307#
//Creates ClientsDetailsList from source file
public static ClientsDetailsList readFile(File inputFile) throws IOException{
ArrayList <String> clientData = new ArrayList<String>();
ArrayList <ClientDetails> cdList = new ArrayList<>();
ArrayList <PolicyList> arrayofPolsLists = new ArrayList<>();
//Lists of ClientDetails fields
ArrayList <Name> clientName = new ArrayList<>();
ArrayList <String> clientID = new ArrayList<String>();
ArrayList <Address> clientAddress = new ArrayList<>();
// Lists of Name class fields
ArrayList <String> clientTitle = new ArrayList<String>();
ArrayList <String> clientInitials = new ArrayList<String>();
ArrayList <String> clientSurname = new ArrayList<String>();
//Lists of Address class fields
ArrayList <String> clientStreet = new ArrayList<String>();
ArrayList <String> clientCity = new ArrayList<String>();
ArrayList <String> clientPostCode = new ArrayList<String>();
ArrayList <ArrayList <Policy>> list = new ArrayList<ArrayList<Policy>>();
Scanner fileScan = new Scanner(inputFile);
fileScan.useDelimiter("#");
int i =0;
//Reading the file
while(fileScan.hasNext()){
clientData.add(fileScan.next());
Scanner cdScan = new Scanner(clientData.get(i));
cdScan.useDelimiter("/");
ArrayList <String> tokens = new ArrayList<String>();
ArrayList <Policy> clientPolicyNo = new ArrayList<>();
while(cdScan.hasNext()){
tokens.add(cdScan.next());
}
clientID.add(tokens.get(0));
clientTitle.add(tokens.get(1));
clientInitials.add(tokens.get(2));
clientSurname.add(tokens.get(3));
clientStreet.add(tokens.get(4));
clientCity.add(tokens.get(5));
clientPostCode.add(tokens.get(6));
boolean whileController = true;
while(whileController){
clientPolicyNo.add(new Policy(tokens.get(7)));
switch(tokens.size()){
case 9 : clientPolicyNo.add(new Policy(tokens.get(8)));
break;
case 10: clientPolicyNo.add(new Policy(tokens.get(8)));
clientPolicyNo.add(new Policy(tokens.get(9)));
break;
case 11: clientPolicyNo.add(new Policy(tokens.get(8)));
clientPolicyNo.add(new Policy(tokens.get(9)));
clientPolicyNo.add(new Policy(tokens.get(10)));
break;
}
whileController=false;
}
list.add(clientPolicyNo);
i++;
}
//Adding policy lists
for(int j =0; j<clientID.size();j++){
arrayofPolsLists.add(new PolicyList());
arrayofPolsLists.get(j).aListOfPolicies=list.get(j);
}
//Creating Name objects
for(int j =0;j<clientID.size();j++){
clientName.add(new Name());
clientName.get(j).Title = clientTitle.get(j);
clientName.get(j).Initials = clientInitials.get(j);
clientName.get(j).Surname = clientSurname.get(j);
}
//Creating Address objects
for(int j =0;j<clientID.size();j++){
clientAddress.add(new Address());
clientAddress.get(j).street = clientStreet.get(j);
clientAddress.get(j).city = clientCity.get(j);
clientAddress.get(j).postcode = clientPostCode.get(j);
}
//Creating ClientDetails
for(int j =0;j<clientID.size();j++){
cdList.add(new ClientDetails());
cdList.get(j).ClientID = clientID.get(j);
cdList.get(j).fullName = clientName.get(j);
cdList.get(j).fullAddress = clientAddress.get(j);
cdList.get(j).clientsPolicies = arrayofPolsLists.get(j);
}
//Creating a ClientDetailsList object
ClientsDetailsList ClientDetList = new ClientsDetailsList();
ClientDetList.aListOfClientDetails = cdList;
return ClientDetList;
}
ClientDetails class has 4 fields:
public String ClientID;
public Name fullName;
public Address fullAddress;
public PolicyList clientsPolicies;
Main method
File clientsFile = new File("ClientDetailsInput");
InputData e = new InputData();
ClientsDetailsList testList = new ClientsDetailsList();
testList = e.readFile(clientsFile);
System.out.println(testList.getClientDetails("IC-x00013A"));
Put a break after found = true;, for example...
public ClientDetails getClientDetails(String givenID) {
boolean found = false;
int index = 0;
for(;index<aListOfClientDetails.size();index++){
if((aListOfClientDetails.get(index).ClientID.equals(givenID))) {
found = true;
break;
}
}
if(found)
return aListOfClientDetails.get(index);
else return null;
}
Or you could simplify it further, by doing away with the need for the index at all, for example
public ClientDetails getClientDetails(String givenID) {
boolean found = false;
int index = 0;
ClientDetails details = null;
for (ClientDetails check : aListOfClientDetails) {
if(check.ClientID.equals(givenID)) {
details = check;
break;
}
}
return details;
}
Updated
After actually been able to read the data, I added
String check = aListOfClientDetails.get(index).ClientID;
System.out.println(givenID + " = " + check);
if ((check.equals(givenID))) {
to the search list and it printed...
IC-x00013A = IC-x00042W
IC-x00013A =
IC-x00033D
IC-x00013A =
IC-x00013A
IC-x00013A =
IC-x00018O
IC-x00013A =
IC-x00037N
IC-x00013A =
IC-x00039A
IC-x00013A =
IC-x00011I
IC-x00013A =
IC-x00025V
IC-x00013A =
IC-x00008L
IC-x00013A =
IC-x00028F
IC-x00013A =
IC-x00031X
IC-x00013A =
IC-x00020C
IC-x00013A =
IC-x00015H
...which freaked me out, until I realised that the ID's were prefixed with a new line character...!
So what I did was add trim to each result from the tokens in the read method...
clientID.add(tokens.get(0).trim());
(I did it for each line, just haven't shown), which then lead to
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 13, Size: 13
at java.util.ArrayList.rangeCheck(ArrayList.java:638)
at java.util.ArrayList.get(ArrayList.java:414)
at testsearch.TestSearch$ClientsDetailsList.getClientDetails(TestSearch.java:47)
at testsearch.TestSearch.main(TestSearch.java:23)
Which is what I expected should happen in your search method...
If we have a closer look at the search loop...
for(;index<aListOfClientDetails.size();index++){
if((aListOfClientDetails.get(index).ClientID.equals(givenID)))
found = true;
}
You should be able to see, that regardless of the state of found, the index will ALWAYS be equal to aListOfClientDetails.size() at the end of the loop, as there is no other exit condition to the loop that takes found into consideration...
Which takes me back to my original suggestions...
Never discount the power of a simple System.out.println statement to check your sanity and a good debugger...
Debugging would have helped i guess.
At the end you are returning
return aListOfClientDetails.get(i);
But you should get index "index" instead of "i" that was never initiated as far as i see.
So replace that with
return aListOfClientDetails.get(index);
And of course dont forget to leave the loop when you find something so index stays the right index.
Or just return the object right after you found it instead of setting found to true.
And last but not least: I dont know ClienID so I cant tell from here but if it does not implement the equals function the you actually will not get it work the way you want. So check what it does and perhaps override it.
Setting the Scanner's delimiter to '#' or '/' causes the line separators \n (whatever it is on your system) to remain in the data. So, some next() method call will eventually produce a String value with a leading \n, which is bound to happen for all IDs from the second one up, if the line structure is aligned with the '#' signs.
The code you have for parsing is extremely complex. I'd advocate to read lines (\n-delimited) and handle one line at a time, using
String[] tokens = line.split( "/" );
and assigning the strings to the destination fields of one object. Avoid the many lists - this only confuses matters.