for Loop repeating itself once, even when told not to - java

I can't for the life of me figure out why this string comparison loop will loop again after even when finding that no values in the array = that value.
Query p = new Query(section).addSort("Login", Query.SortDirection.DESCENDING) ;
PreparedQuery qp = datastore.prepare(p);
int listSize = 0;
for(Entity amount : qp.asIterable()){
listSize++;
}
for (Entity result2 : qp.asIterable()) {
if (breakOff==true) {
break;
} else {
System.out.println("1stloop size is " + size + result2.getProperty("Login"));
MyBean temp2 = new MyBean();
temp2.setData((String) result2.getProperty("Login"));
Query q = new Query("sent").addSort("Login", Query.SortDirection.DESCENDING);
PreparedQuery pq = datastore.prepare(q);
int i = 0;
for (Entity result : pq.asIterable()) {
i++;
System.out.println("2ndloop is "+ result.getProperty("Login"));
MyBean temp = new MyBean();
temp.setData((String) result.getProperty("Login"));
if (temp.getData().equals(temp2.getData())) {
System.out.println("broken");
break;
} else if (i >= size) {
sentNum.setData(temp2.getData());
Entity logins = new Entity("sent");
logins.setProperty("Login", temp2.getData());
datastore.put(logins);
System.out.println("sizematch wrote " + temp2.getData());
breakOff = true;
} else {
System.out.println("increase" + i);
}
}
}
}
As you can see, I call a breakOff==true so the loop wouldn't go through it again, but it always does. Once exactly.

Well, look at the place you check if you need to break, it is in the start of the loop. That means that the program will break in the next enter to the loop, so it will run one more time exactly.
To fix it, just change the statement location to the end of the second loop.
here is your fixed code: (by the way it is a mess, try to organize it a bit)
Query p = new Query(section).addSort("Login", Query.SortDirection.DESCENDING) ;
PreparedQuery qp = datastore.prepare(p);
int listSize = 0;
for(Entity amount : qp.asIterable()){
listSize++;
}
for (Entity result2 : qp.asIterable()) {
System.out.println("1stloop size is " + size + result2.getProperty("Login"));
MyBean temp2 = new MyBean();
temp2.setData((String) result2.getProperty("Login"));
Query q = new Query("sent").addSort("Login", Query.SortDirection.DESCENDING);
PreparedQuery pq = datastore.prepare(q);
int i = 0;
for (Entity result : pq.asIterable()) {
i++;
System.out.println("2ndloop is "+ result.getProperty("Login"));
MyBean temp = new MyBean();
temp.setData((String) result.getProperty("Login"));
if (temp.getData().equals(temp2.getData())) {
System.out.println("broken");
break;
} else if (i >= size) {
sentNum.setData(temp2.getData());
Entity logins = new Entity("sent");
logins.setProperty("Login", temp2.getData());
datastore.put(logins);
System.out.println("sizematch wrote " + temp2.getData());
breakOff = true;
break;
} else {
System.out.println("increase" + i);
}
}
if (breakOff)
break;
}
notice that there is no reason to check if(breakOff==true) as you can also check if(breakOff) and get the same answer. The reason is that breakOff==true will give you true if and only if breakOff is true, but if(breakOff) will be true if and only if breakOff is true, so they are same.

Related

I need help making prims algorithm the way my instructor wants

So i have checked through the previously posted prims algorithm posts. and i cant find one that satisfies my teachers requirements. I worked on this code with him, and have it mostly working. however for somereason when it gets to a certian point, it breaks and goes to the wrong edge.
'''public int prims(T startVertex) {
int tempWeight = 0;
int championWeight = 0;
int totalWeight = 0;
int i = 0;
boolean firstOne = false;
T championVertex = null;
T currentVertex = null;
T checkVertex = null;
T championMarked = null;
UnboundedQueueInterface<T> vertexQueue = new LinkedUnbndQueue<T>();
clearMarks();
markVertex(startVertex);
currentVertex = startVertex;
do {
for (int y = 0; y < numVertices; y++) {
currentVertex = vertices[y];
if (isMarked(currentVertex)) {
championWeight = 0;
championVertex = null;
checkVertex = null;
firstOne = true;
vertexQueue = getToVertices(currentVertex);
while (!vertexQueue.isEmpty()) {
checkVertex = vertexQueue.dequeue();
if ((!(isMarked(checkVertex)))) {
tempWeight = weightIs(currentVertex, checkVertex);
if (championWeight > tempWeight || firstOne == true) {
championWeight = tempWeight;
championVertex = checkVertex;
championMarked = currentVertex;
firstOne = false;
}
}
}
}
}
System.out.println((String) championMarked + (String) championVertex + championWeight);
markVertex(championVertex);
totalWeight += championWeight;
} while (!(getUnmarked() == null));
System.out.println("Total cost is " + totalWeight);
return totalWeight; '''
when i run it i get the following output
Graph 1
AD1
DF4
FC3
FE12
FZ17
Enull0
the output is correct for the graph until the line FE12. it should be CE4. when i run debug, i watch the code find the answer, but then jumps up to the for loop and looses the right answer. I know there is an error in my logic, but I cant quite figure it out. Your input is appreciated. thanks
So i have figured out my issue, I needed to put the resets for the code, after the code outputs the solution, otherwise where they were, if there were any vertices left to check that were not used already, the code would loose the current values.
they needed to go here
'''System.out.println((String) championMarked + (String) championVertex +
championWeight);
markVertex(championVertex);
totalWeight += championWeight;
championWeight = 0;
championVertex = null;
checkVertex = null;
firstOne = true;
} while (!(getUnmarked() == null));'''

Problem with program not catching duplicate Strings and correct processing

Assume I have an ArrayList of food objects foodList. My program does not catch duplicate Strings when I am reading a file, and I'm not exactly sure why. If the String "oil" appears twice in my file, my program creates a new object, when I don't want it to since it should exist in my ArrayList after it reads the first String "oil"
while(recipeFile.hasNext())
{
String ingredient = recipeFile.nextLine();
//System.out.println("line " +ingredient );
ingredient = ingredient.toLowerCase().trim();
if (ingredient.equals("---"))
{
isIngredient = !isIngredient;
}
else if (isIngredient)
{
boolean found = false;
for(int i = 0; i<foodList.size(); i++)
{
Food food2Compare = foodList.get(i);
//System.out.println("comparing " + food1.getFoodName() +" and " +ingredient );
int currentFreq = food2Compare.getFrequency();
if(food2Compare.getFoodName().contains(ingredient) &&!found)
{
food2Compare.setFrequency(currentFreq+1);
found = true;
}
}
if (found == false)
{
ingredient = ingredient.substring(ingredient.lastIndexOf(" ")+1);
if(ingredient.substring(ingredient.length() - 1).equals("s"))
{
ingredient = ingredient.substring(0, ingredient.length() - 1);
}
else if(ingredient.substring(ingredient.length() - 2, ingredient.length() - 1).equals("es"))
{
ingredient = ingredient.substring(0, ingredient.length() - 3);
}
System.out.println("line " +ingredient );
foodList.add(new Food(ingredient, 1));
Collections.sort(foodList);
}
}
}
Replace food2Compare.getFoodName().contains(ingredient) with ingredient.contains(food2Compare.getFoodName()).

How to sort a linked list with objects and private variables

I am going to be honest and up front here. This is homework, but I have become desperate and am looking for anyone to assist me. I have been working on this off and on for over a month and have gone to my instructor multiple times. Basically this program needs to create and sort a linked list that has an int, string and double in each node. It needs to be able to sort by each data type as well as print in input order but once I figure one out I can transfer it to the other data types. Please, everything needs to be "hand made", please do not use any built in commands as I need to create everything as per my instructor's demands.
I attempted to make the linked list and then sort it, but I ran into a problem so I decided to try and sort the list as I create it.
For example: Input the first node, then input the next node in front/behind the first, then put the next where it needs to go... and so forth.
Here is my code (I only focus on the strings):
String repeat = "y";
list1 fChr = null;
list1 p = fChr;
list1 copy = null;
//list1 dCopy = null;
//list1 iCopy = null;
list1 fd = fChr;//front of the double list
list1 fi = fChr;//front of the integer list
list1 fStr = fChr;//front of the string list~
list1 pStr = fStr;
boolean inserted = false;
int iii = 0;
String sss = "";
double ddd = 0.0;
while(repeat.equals("y"))//while the user agrees to adding a new node
{
if(fChr == null)// if the front is empty
{
fChr = new list1();//create a new node by calling object and sets it as the front
p = fChr;
copy = fChr;
sss = fChr.GetS();
iii = fChr.GetI();
ddd = fChr.GetD();
copy.SetS(sss);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println("(1)");
}
else
{
System.out.println("(2)");
if(p!=null)
{
System.out.println("p = "+ p.GetS());
if(p.next != null)
{
System.out.println("p.next = "+ p.next.GetS());
System.out.println("p.next.next = "+ p.next.next.GetS());
}
}
p = fChr;
while(p.next != null)//finds the end of the Linked list
{
System.out.println("(3)");
p = p.next;//moves the pointer p down the list
}
list1 NextNode = new list1();//
p.next = NextNode;
sss = NextNode.GetS();
iii = NextNode.GetI();
ddd = NextNode.GetD();
copy = NextNode;
String gg = "hi";//tests to see if the setter is actually changing the value inside copy(it is not, it prints b)
copy.SetS(gg);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println(copy.GetS());
System.out.println("p = "+ p.GetS());
}
pStr = fStr;
//System.out.println(copy.GetS()+"*");
inserted = false;
if(fStr == null)
{
System.out.println("(4)");
fStr = copy;//fStr = fChr;
inserted = true;
//System.out.println("p.next.next = "+ p.next.next.GetS());
}
else if(copy.GetS().compareTo(fStr.GetS()) < 0)
{
System.out.println("(5)");
//System.out.println("1)p.next.next = "+ p.next.next.GetS());
copy.next = fStr;//ERROR ON THIS LINE
System.out.println("2)p.next.next = "+ p.next.next.GetS());
System.out.println("fChr.next: "+fChr.next.GetS());
fStr = copy;
System.out.println("3)p.next.next = "+ p.next.next.GetS());
inserted = true;
System.out.println("p = "+ p.GetS());
System.out.println("p.next = "+ p.next.GetS());
System.out.println("4)p.next.next = "+ p.next.next.GetS());
}
else if(fStr.next == null && fStr != null)
{
System.out.println("(6)");
fStr.next = copy;
inserted = true;
}
else
{
System.out.println("(7)");
pStr = fStr;
System.out.println("RIP (8)");
while(pStr.next != null && inserted == false)
{
System.out.println("(9)");
System.out.println("RIP");
if(copy.GetS().compareTo(pStr.next.GetS()) < 0)//if it goes between 2 nodes
{
System.out.println("(10)");
copy.next = pStr.next;
pStr.next = copy;
inserted = true;
}
else
{
System.out.println("(11)");
pStr = pStr.next;
}
if(pStr.next == null && inserted == false)// it goes at the end(not necessary bc of the (in order) part)
{
System.out.println("(12)");
pStr.next = copy;
}
}
}
repeat = JOptionPane.showInputDialog("Would you like to add a node [y/n]");
System.out.println("End of Loop");
}
System.out.println(fStr.GetS());
PrintMenu(fChr, fi, fd, fStr);// sends the user to the menu screen
}
From all of my print statements I have (what I think) found the problem. This code runs through twice and upon hitting "y" for the third time, prints "(3)" in an infinite loop. I have found that (say the input for the strings is "c" then "b") "p" is equal to "c", p.next is equal to "b" and p.next.next is equal to "c". So, p is in an infinite loop. I have no idea why it does this, I have a theory that it could be because the front(fChr) changes and then "p" points to it and is just kinda drug along. I also just realized that me trying to set "copy" equal to "NextNode" was unsuccessful and copy just holds the value inside p.next(which is NextNode). That seems correct, but when I try to put something else in, it doesn't work. I could be testing this incorrectly and in that case the setter is correct. Setting is one of the main problems that I seem to be having. I will try to answer as many questions as I can if anyone has any.
Also here is the object in case you would like to see it. Thank you for your time, any help will be appreciated. Please if possible try to keep it relatively simple this is a high school assignment and I am so close and am stumped on how to fix what is wrong. Also, you may have noticed, but I have to use private variables. I am not asking for someone to give me a program that works, I am just asking if you know why what is going wrong is happening and if you know how to fix it. Thank you from the bottom of my heart!
import javax.swing.JOptionPane;
public class list1
{
private int i;
private String s;
private double d;
private String ss = null;
private int ii = 0;
private double dd = 0.0;
list1 next = null;
public list1()
{
String str;
s=JOptionPane.showInputDialog("Enter a String");
String temp =JOptionPane.showInputDialog("Enter an Integer");
i = Integer.parseInt(temp);
String temp2 =JOptionPane.showInputDialog("Enter a Double");
d = Double.parseDouble(temp2);
}
public double GetD()
{
return d;
}
public String GetS()
{
return s;
}
public int GetI()
{
return i;
}
public void SetS(String x)
{
ss = x;
}
public void SetI(int y)
{
ii = y;
}
public void SetD(double z)
{
dd = z;
}
}

Converting an iterative function to recursive

I am trying to convert an iterative function to Recursion.
But once I tried to do that it is runnning continuously like an infinite loop.
This is my iterative code
private static Node buildModelTree(String[] args) {
// TODO Auto-generated method stub
String clsIndex = args[3];
splitted.add(currentsplit);
double entropy = 0;
int total_attributes = (Integer.parseInt(clsIndex));// class index
int split_size = splitted.size();
GainRatio gainObj = new GainRatio();
while (split_size > current_index) { //iterate through all distinct pair for building children
currentsplit = (SplitInfo) splitted.get(current_index);
System.out.println("After currentsplit --->" + currentsplit);
gainObj = new GainRatio();
int res = 0;
res = ToolRunner.run(new Configuration(),new CopyOfFunID3Driver(), args);
gainObj.getcount(current_index);
entropy = gainObj.currNodeEntophy();
clsIndex = gainObj.majorityLabel();
currentsplit.classIndex = clsIndex;
if (entropy != 0.0 && currentsplit.attr_index.size() != total_attributes) { //calculate gain ration
bestGain(total_attributes,entropy,gainObj);
} else {
//When entropy is zero build tree
Node branch = new Node();
String rule = "";
Gson gson = new Gson();
int temp_size = currentsplit.attr_index.size();
for (int val = 0; val < temp_size; val++) {
int g = 0;
g = (Integer) currentsplit.attr_index.get(val);
if (val == 0) {
rule = g + " " + currentsplit.attr_value.get(val);
//JSON
// branch.add(g, currentsplit.attr_value.get(val).toString(), new Node(currentsplit.classIndex, true));
} else {
rule = rule + " " + g + " "+ currentsplit.attr_value.get(val);
//branch.add(g, currentsplit.attr_value.get(val).toString(), buildModelTree(args));
}
}
rule = rule + " " + currentsplit.classIndex;
}
split_size = splitted.size();
current_index++;
}
}
where all should I make change?
I am trying to build tree. So inoredr to get the tree structure I am trying to make my id3 code recursive.
with my current code I am only getting output as this ,But I want it as tree structure
Please suggest.
The Recursion algorithm must have following
1.Each time the function invokes itself, the Problem size has to be reduced.
(ie. If suppose first you are calling the function with array of size n, then the next time it has to be lesser than n.
Base Case - the condition for the return statement.
(For example, if the array size is 0 then return)
In your code, these two are missing.
You're keep on calling the function with the same size of array. That's the problem.
Thanks

Linked list looping and addfirst

Why this is not working? I am looping on a trxFifoArray List and passing its object items to result List. I need to split some amounts in 2 so I need to addFirst this 2 amount to result list. The amounts are in an arrayList [-9.0000, -6.0000]. So I loop the amount list to do the addFirst on result and the items are added but with same amount even the list has 2 different amount.
LinkedList<InvtQaTracer> trxFifoArray = new LinkedList<InvtQaTracer>();
LinkedList<InvtQaTracer> result = new LinkedList<InvtQaTracer>();
InvtQaTracer trx = new InvtQaTracer();
int trxDocoRef = 0;
for (int j = list.size() - 1; j >= 0; j--) {
trx = list.get(j);
System.out.printf("%12.4f %4s%10d %12s%n", trx.getTrxQty(), trx.getDocType(), trx.getOrdNo(), trx.getLocNo());
List<BigDecimal> auxAmounts = new ArrayList<BigDecimal>();
if (trx.getDocType().compareTo("OV") == 0
|| trx.getDocType().compareTo("XV") == 0) {
//Do something ...
} else {
BigDecimal auxAmount = BigDecimal.ZERO;
Boolean needRemove = false;
for (InvtQaTracer tFifo : trxFifoArray) {
if (trx.getDocType().compareTo("IT") == 0) {
auxAmounts.add(tFifo.getTrxQty().negate());
}
}
if (needRemove) {
Iterator<InvtQaTracer> iterator = trxFifoArray.iterator();
int count = 0;
while (iterator.hasNext()) {
InvtQaTracer iqt = iterator.next();
if (iqt.getTrxQty().compareTo(BigDecimal.ZERO) == 0) {
count++;
iterator.remove();
}
}
}
}
if (!auxAmounts.isEmpty()) {
for (BigDecimal asss : auxAmounts) {
System.out.println(asss);
trx.setTrxQty(asss);
result.addFirst(trx);
}
} else {
result.addFirst(trx);
}
for (InvtQaTracer invtQT : trxFifoArray) {
System.out.printf("%20s%2s%12.4f %10d %12s%10d%n", " ----------------> ", invtQT.getDocType(), invtQT.getTrxQty(), invtQT.getOrdNo(), invtQT.getLocNo(), invtQT.getDocNo());
}
}
This code add two records with -6.000000 value even it is printing out both of them. I hope you understand the code. Please Help!!!
Thanks.
Thanks for any help!
Am finding a problem in the code.
Code needs to be updated like this
if (!auxAmounts.isEmpty()) {
LinkedList<InvtQaTracer> result = new LinkedList<InvtQaTracer>();
//Updated Here
InvtQaTracer trx = null;
List<BigDecimal> auxAmounts = new ArrayList<BigDecimal>(); //[-9.000000, -6.000000]
for (BigDecimal asss : auxAmounts) {
System.out.println(asss);
//Updated Here
trx = new InvtQaTracer();
trx.setTrxQty(asss);
result.addFirst(trx);
}
} else {
result.addFirst(trx);
}
One more change identified is
inside the else loop needRemove value is set to false by default and below checking whether it is true in if loop. think this one can be removed.

Categories