java : How to get Internal details inside for loop - java

public void two(final BeanForm[] captureddata)
{
for (BeanForm form : captureddata)
{
if (form.getCyclicType() != null)
{
logger.info("The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info("The Ticket Type is"+ form.getTicketType().value());
}
}
}
The above code works fine, but the output what I can see in the log file is (In case the length of the BeanForm is 2 )
11/Nov/2011 20:15:51 - The Cyclic Type is DTI
11/Nov/2011 20:15:51 - The Ticket Type is MMTS
11/Nov/2011 20:15:51 - The Cyclic Type is DTI
11/Nov/2011 20:15:51 - The Ticket Type is MMTS
I just wanted to know whether it is possible to get the array details also, like to which array this data belongs to
For example
The array[1] Cyclic Type is DTI
The array[2] Cyclic Type is SAG

Just use an external count:
public void two(final BeanForm[] captureddata)
{
int count = 0;
for (BeanForm form : captureddata)
{
if (form.getCyclicType() != null)
{
logger.info(count + " The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info(count + " The Ticket Type is"+ form.getTicketType().value());
}
count++;
}
}
or as a normal for loop
public void two(final BeanForm[] captureddata)
{
for (int i=0; i<captureddata.length; i++)
{
BeanForm form = capturedata[i];
if (form.getCyclicType() != null)
{
logger.info(i+ " The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info(i+ " The Ticket Type is"+ form.getTicketType().value());
}
}
}

If you mean the index into the loop - no. You'd need to do that explicitly:
for (int i = 0; i < capturedData.length; i++)
{
BeanForm form = capturedData[i];
// Now you have both form and i.
}

One possible approach is to maintain a counter in the for-loop and you can use the counter along with the array[], something like:
int i=0;
for-each loop
{
//print array[i]
//increment i
}

public void two(final BeanForm[] captureddata)
{
for (i = 0; i < captureddata.length(); i++) {
BeanForm form = captureddata[i]
if (form.getCyclicType() != null)
{
logger.info("The array["+i+"] Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info("The array["+i+"] Ticket Type is"+ form.getTicketType().value());
}
}
}

agree with Matthew's solution
, simply use another counting number and make an increment at the end of the loop.
however, in the log file, do mind whether you wish to start with the "array[0]" or "array[1]"

Related

Observe livedata inside a for loop

I want to update a list in my activity that depends on the data of another list. Both the data list are being observed from the activity from the my viewmodel. After I get the data from my firstlist I need to run a for loop on this list to get the required ids and get the data for the second list.
But keeping the livedata observer in the for loop is causing a lot of problems. The for loop runs as expected but the livedata observer is getting called almost double the amount of the for loop. This happens only the first time when the list in being brought from the api. When I do the same operation a second time where the list is cached and is being brought from the database, the problem does not occur. Below is the source code for the problem,
for (int i = 0; i < firstList.size(); i++) {
final String uId = firstList.get(i).item.uid;
final long id = firstList.get(i).item.id;
viewModel.initAnotherItemRepository(uId, id);
viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
#Override
public void onChanged(Resource<List<SecondItem>> listResource) {
if (listResource.data != null) {
secondItemList.addAll(listResource.data);
if (count == firstList.size() - 1) {
//Do something
}
count = count + 1;
}
if (listResource.state == Resource.STATE_FAILURE) {
showLoadingSpinner(false);
}
}
}
);
}
Try to observe SecondItem outside the for loop. It gets data whenever update
viewModel.getSecondItem().observe(this, new Observer<Resource<List<SecondItem>>>() {
#Override
public void onChanged(Resource<List<SecondItem>> listResource) {
if (listResource.data != null) {
secondItemList.addAll(listResource.data);
if (count == firstList.size() - 1) {
//Do something
}
count = count + 1;
}
if (listResource.state == Resource.STATE_FAILURE) {
showLoadingSpinner(false);
}
}
}
);
for (int i = 0; i < firstList.size(); i++) {
final String uId = firstList.get(i).item.uid;
final long id = firstList.get(i).item.id;
viewModel.initAnotherItemRepository(uId, id);
}

Validating user input in arrays

Hey guys I am doing a project for school and am having a little trouble, I have a variable "reservationNumber" and im attempting to check if the number the user inputs is in the array, if not it returns a string saying the number was not found. It is working fine and displays the correct info when there is a valid input but when an invalid input is detected it gives a null.pointer.exception error. I tried writing it so that if the number is not detected the private method returns -1, then when I call the tickerInformation method, if that the variable 'ticket' returns -1 then it returns "invalid reservation number". This is where is error is being raised and only occurs when I enter an invalid number please help.
public void ticketInformation(String reservationNumber)
{
int ticket = searchArray(reservationNumber);
if (ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
private int searchArray(String reservationNumber)
{
for (int i = 0; i < ticketSale.length; i++)
{
if (ticketSale[i].getReservationNumber().equals(reservationNumber))
{
return i;
}
}
return -1;
}
ticketSale[i].getReservationNumber().equals(reservationNumber) has an issue. Share the declaration and init for array "ticketSale". If ticketSale array is for abstract data type then why equal is called with String?
You didn't post the whole code but I think that when you enter invalid number as reservation number, it does not assigned to the related object's instance variable. So getReservationNumber() might be returning null.
Add a null check,
private int searchTicketSales(String reservationNumber) {
int reservationNumberIndex = -1;
for (int i = 0; i < ticketSale.length; i++) {
if (null != ticketSale[i].getReservationNumber() && ticketSale[i].getReservationNumber().equals(reservationNumber)) {
reservationNumberIndex = i;
break;
}
}
return reservationNumberIndex;
}
Best Regards,
Rakesh
Add a regex to validate that your input is a valid number "\\d+":
public void ticketInformation(String reservationNumber)
{
String regex = "\\d+";
if(!reservationNumber.matches(regex))
{
System.out.println("The reservation number entered was n0t found");
}
int ticket = searchArray(reservationNumber);
if(ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
You might want to validate searchArray, particularly if it is not used interdependently from ticketInformation().

ArrayList vs. Array. Why is one working and one isn't?

I've been trying to switch an older assignment over from an array to an arraylist, but for whatever reason my find method is not working when I modify it to use arrayList.. Seems to always be returning -1.
This is part of a large class so I don't want to include everything unless completely necessary, but I did include the declarations in case they are important:
public class Switch {
private SwitchEntry[] camTable;
private int numEntries;
private int maxEntries;
public Switch() {
camTable = new SwitchEntry[100]; // default value
numEntries = 0;
maxEntries = 100;
}
public Switch(int maxEntries) {
camTable = new SwitchEntry[maxEntries];
numEntries = 0;
this.maxEntries = maxEntries;
}
Original:
public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable[i].getAddress())){
found = i;
break;
}
return found;
}
Modified:
public int find (MACAddress source) {
int found = -1;
for (int i=0; i < numEntries; i++)
if (source.isEqual (camTable.get(i).getAddress())){
found = i;
break;
}
return found;
}
Where numEntries is modified & where the new entries are added into the arrayList:
public void processFrame(Frame inFrame) {
// first, add source MAC to camTable if not already there
if (find(inFrame.getSource()) == -1) {
if (numEntries >= maxEntries) {
System.out.println ("Error...camTable is full - cannot add " + inFrame.getSource());
} else {
camTable.add(new SwitchEntry(inFrame.getSource(), inFrame.getPort())); //PROBLEM LINE
System.out.println ("Adding " + inFrame.getSource() + " to camTable");
}
}
//process frame
int index = find(inFrame.getDestination());
if (index != -1){
System.out.print ("Sending frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out port " + camTable.get(index).getPort() );
} else {
System.out.print ("Flooding frame with data " + inFrame.getData() + " from " + inFrame.getSource() + " to " + inFrame.getDestination());
System.out.println (" out all ports" );
}
}
Solution:
camTable.add(numEntries++, new SwitchEntry(inFrame.getSource(),inFrame.getPort()));
Try This
public int find (MACAddress source) {
int found = -1;
ArrayList<MACAddress> camTable = new ArrayList<MACAddress>();
ListIterator<MACAddress> itr = camTable.listIterator();
while(itr.hasNext()){
MACAddress tempAdd = itr.next();
if(source.getAddress().equals(tempAdd.getAddress())){
found = itr.nextIndex();
return found;
}
return found;
}
I assume in ArrayList you store the objects of MACAddress. in if condition i check the source.getAddress to tempAdd.getAddress() is same then it will retun index of ArrayList. here ArrayList is local variable but you can create as a class variable
Use Contain method of collection.(ArrayList)
http://www.tutorialspoint.com/java/util/arraylist_contains.htm
Solution was straight-forward and just an oversight by me. All I had to do was add numEntries back into my add statement, which I neglected to fix after changing from an array to arrayList
Solution is posted in the original question now:

Why is this array giving a null pointer exception?

I'm trying to implement a dictionary with a hash table (not using Java's provided hash table classes, but rather made from scratch). Below is the find() method from my Dictionary class, used to detect whether or not a key is in the table when inserting/removing. If the key is already in the table, it returns a score associated with the key (elements in the table are inserted as pairs of key/score into LinkedLists in each table position). If not, it returns -1.
I am running a supplied test program to determine if my Dictionary class works, but I am encountering a NullPointerException when reaching a certain point. Included below is the particular test. Why would this exception be coming up? (I can provide more code if needed!)
Find:
public int find(String config) {
for (int i = 0; i < dictSize; i++) {
if (dict[i] != null) {
LinkedList<DictEntry> current = dict[i];
String currentConfig = current.peek().getConfig(); //Dictionary.java:66
if (currentConfig.equals(config)) {
int currentScore = current.peek().getScore();
return currentScore;
}
}
}
return -1;
}
Insert:
public int insert(DictEntry pair) throws DictionaryException {
String entryConfig = pair.getConfig();
int found = find(entryConfig); //Dictionary.java:27
if (found != -1) {
throw new DictionaryException("Pair already in dictionary.");
}
int entryPosition = hash(entryConfig);
if (dict[entryPosition] == null) { //Dictionary.java:35
LinkedList<DictEntry> list = new LinkedList<DictEntry>();
dict[entryPosition] = list;
list.add(pair);
return 0;
} else {
LinkedList<DictEntry> list = dict[entryPosition];
list.addLast(pair);
return 1;
}
}
The test:
// Test 7: insert 10000 different values into the Dictionary
// NOTE: Dictionary is of size 9901
try {
for (int i = 0; i < 10000; ++i) {
s = (new Integer(i)).toString();
for (int j = 0; j < 5; ++j) s += s;
collisions += dict.insert(new DictEntry(s,i)); //TestDict.java:69
}
System.out.println(" Test 7 succeeded");
} catch (DictionaryException e) {
System.out.println("***Test 7 failed");
}
Exception stack trace:
Exception in thread "main" java.lang.NullPointerException
at Dictionary.find(Dictionary.java:66)
at Dictionary.insert(Dictionary.java:27)
at TestDict.main(TestDict.java:69)
peek() returns null that's why. You can have a nullity check prior to getConfig() call.

Searching in a java arraylist without returning a value

Ive been trying to change my method to a void. But whenever I change it, it always prints out the book name and an error message. How can I change my method to a void?
public int displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
return i;
}
}
return -1;
System.out.println ("Book name is not valid");
}
You need to remove the return statements (and replace the first one by a simple return (no parameter)) too.
public void displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
//removed return i;
return;
}
}
// removed return -1;
System.out.println ("Book name is not valid");
}
Try something like this, I am sure it will work:
public void displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
return; // modified here
}
}
// modified here
System.out.println ("Book name is not valid");
}
You probably still want to return when you've found the book - that may be what you've missed before:
public void displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
return;
}
}
System.out.println ("Book name is not valid");
}
Personally I'd probably separate out the "search" from "display":
public Library getBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
return library;
}
}
return null;
}
public void displayBookDetails(String bookName) {
Library bookDetails = getBookDetails(bookName);
if (bookDetails == null) {
System.out.println ("Book name is not valid");
} else {
System.out.println(bookDetails.returnBookName());
System.out.println(bookDetails.authorName());
}
}
(Note that there's no such thing as the "index" at this point, of course. If you really need to display that as well, it would need to be part of Library.)
You can do so by using return without a value:
System.out.println(library.authorName());
return;
}
The return type you are trying to change to void only signifies what is returned by the method. However the method might have different side-effects like I/O, e.g. printing to the console. Unfortunately there is no way to constrain side-effects in Java or most OOP langauges. Functional programming aims at getting rid of all side effects in your functions, so it can be reasoned about the program more easily.

Categories

Resources