Java program evaluating twice - java

public Iterator<IBookItem> findBooksBySeller(String seller) {
for(int i = 0; i < sellerList.size(); i++){
if(sellerList.get(i).equals(seller))
{
System.out.println("The seller: " + seller + " has the following books for sale: " + titleList.get(i) + " £" + priceList.get(i));
System.out.println("-----------------------------------------------");
}
}
System.out.println("The Seller: " + seller + " has no Books for Sale");
System.out.println("--------------------------------------------");
return null;
}
This is my code and it prints out both statements, could someone pleases tell me why?

The first statement will be executed if the condition is true for some iteration of the loop. The second statement is always printed after the loop ends (since there's no return statement inside the loop).
You are probably missing a return statement inside your if statement.

At no point are you doing anything to prevent the 2nd group of println's from executing.
You could try adding a return null; after your first group of println's.

Since you have excluded the bottom portion of your code from an else clause, it will be printed regardless of whether or not the if clause is executed. Anything outside of an if-else clause is always executed.

Add a 'return statement' at the end of the 'for' loop.

Related

Python decrement the variable inside for loop

i converted my java code into a python code and how to decrement the variable inside of the for loop in the python? I try to decrease the index by 1 if it is inside the if statement, but apparently I can't do that. Is there any other way that I can decrease i in a for loop?
Java Code:
for(int i = 1; i <= 3; i++)
{
System.out.print("Enter Movie " + i + " of " + 3 + " : ");
String inputMovie = sc.nextLine();
if (inputMovie.equals(""))
{
System.out.println("Please input a movie name.");
System.out.println("");
i--;
}
else
movies.offer("'"+inputMovie+"'");
}
Python Code:
for i in range(1,4):
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
pass
else:
movies.append(inputMovie)
pass
Output: well if we look at the output it is still incrementing not decrementing the i
Enter Movie 1 of 3 :
Please input a movie name
Enter Movie 2 of 3 :
Please input a movie name
Enter Movie 3 of 3 :
Please input a movie name
Python doesn't let you alter the iterator in a for loop. As soon as the next iteration of the loop comes by, the iterator will be the next value of the iterable.
This is also because range doesn't behave like an actual Java-like for loop. Instead, it keeps generating numbers within the range (you can see this by typing list(range(10)) in a Python interpreter, it will make a list of numbers from 0 to 9.
If you want to modify the iterator, you should go old-school with a while loop instead:
i = 1
while i <= 3:
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
else:
movies.append(inputMovie)
i = i + 1
This should do the same as your Java code, as I'm just moving the three instructions from the Java for loop to their places. Notice pass is not required as it is a statement with no effect.
For the sake of optimization, let me say you don't really need to decrement the iterator, just avoid incrementing it instead. I keep this solution separate from the original answer since it is a significant deviation from your original design:
i = 1
while i <= 3:
inputMovie=input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
else:
movies.append(inputMovie)
i = i + 1
All I've done is remove the decrement and push the increment to the else block so it is only run if a movie name has been input.
The for loop in Python is more like for-each. So the loop value(i) will get updated to the next value regardless of the changes/updates in the loop.
A better way to do this would be to use a while loop.
i = 1
while i <= 3:
inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie=="":
print("Please input a movie name")
print("")
i-=1
pass
else:
movies.append(inputMovie)
i+=1
pass
you should use a while statement
"Unfortunately" the for loop will keep "memory" and reassign to the next value at each iteration
i = 1
while i < 4:
inputMovie = input("Enter Movie " + str(i) + " of " + str(3) + " : ")
if inputMovie == "":
print("Please input a movie name")
print("")
i-=1
else:
movies.append(inputMovie)
i+=1
the pass instruction is irrelevant, you can omit that
pass statement
range(low,high) generates a sequence consisting of elements starting from low and ending at high-1. That's why your i-=1 doesn't work, since I is iterating in that list.
The easiest alternative here would be to use a while loop.
while i<target:
if something:
#do something
i += 1
You have to set your range() function correctly. In order to decrement the loop you can use while loop or you can change your algorithm and set the for loop but now what you can do is if you can select the range functions step value to -1. Please try it to check the code coz i also have the same question in mind like you.

Scanner return no new line in a while loop

Snippet of the code
while(!((input = sc.nextLine()) != null)) {
sc = new Scanner(input).useDelimiter(" ");
while (sc.hasNextLine()) {
in[index] = sc.next();
index++;
}
if (index < 3 || !in[0].equals("ping")) {
throw new IllegalArgumentException(
"Usage ping <destination> <port number missing> . . . ."
+ in[0] + " " + in[1] + " " + in[2]);
}
}
I want to keep reading user inputs but after the first iteration, i get no new line found. Scanner does not wait for the user input but rather advances on.
Thanks
Your top-level while loop is doing the opposite of what you want. First it sets input equal to sc.nextLine(), which is good. Then input is compared to null. If this comparison yields true, then you have input, which means that the loop should continue. However, you are then negating the result of that comparison, which makes the loop terminate when there is input.
Remove the exclamation point, and you should be good.
EDIT
On second thought, your inner while loop is exiting when sc.hasNextLine() returns false. After that, you will go through the conditional statement and return to the top. Since sc.hasNextLine() already returned false, of course sc.nextLine() will return null. The input has already ended in the inner loop, so the outer loop will exit as well.

Confused with variable scope for this particular program

This is a snippet of my code. I already fixed this bug, but I just don't understand why it works now. I'm not sure if I explained this correctly, so please ask any question if necessary. The bug is that the variable puncation changes to the correct value test when the statement is located in the place where I commented, the statement works. But, it does not work when the statement is located in the place where I commented, the statement does not work.
if (endOfSen) {
/////////////////The statement below works when it is here./////////////
/////////////////OUTPUT 1 - occurs when the statement is placed here.
String puncation = null ;
/////////////////////
int orgSize = words.size(); //remember size of stack
//only runs if stack is not empty
if (!words.empty()) {
while (words.size() > 0) { //until last word
String word = words.pop();
///The statement below does not work when it is here///////
//////OUTPUT 2- occurs when the statement is placed here.
//String puncation = null ;
//if last word of sentence
if (orgSize == words.size() + 1) {
word = word.substring(0, 1).toUpperCase() + word.substring(1);
puncation = "test"; // just a test value
word = word.replace(puncation, "");
//////////////////test to see if works
System.out.println("puncation: " + puncation);
}
//if first word of sentence
if (words.size() == 0) {
//////////////////test to see if works
System.out.println("puncation: " + puncation);
word = word.toLowerCase();
word = word + "" + puncation;
}
newSen.push(word);
}
}
endOfSen = false;
}
}
OUTPUT 1 (Second puncation changes from original value)
puncation: test
puncation: test
Output 2 (Second puncation does not change from original value)
puncation: test
puncation: null
If the variable is declared inside the loop, then each iteration of the loop will see a different variable. Besides, you even initialize it to null when there, so each iteration will start with a null value.
When declared to null outside the loop, the variable will retain the value from previous iteration(s) of the loop.
Since orgSize never changes in the loop, and words shrinks by one each iteration, the first if statement can only ever be true on the first iteration. Second if statement can only ever be true on the last iteration.
So if puncation is initialized to null inside the loop, the only time it can be not null in the second if statement would be if words originally had size 1.
Simple debugging could have shown you all this.
This is not as much a scoping issue as it's just that the variable is being reset in the loop. I made an example below that is more explicit about the value being reset.
if (endOfSen) {
/////////////////The statement below works when it is here./////////////
/////////////////OUTPUT 1 //////////////////
String puncation = null ;
/////////////////////
int orgSize = words.size(); //remember size of stack
//only runs if stack is not empty
if (!words.empty()) {
while (words.size() > 0) { //until last word
String word = words.pop();
///The statement below does not work when it is here///////
/////////////////OUTPUT 2 //////////////////
// Puncation is beign reset here, each iteration of the loop
puncation = null ;
//if last word of sentence
if (orgSize == words.size() + 1) {
word = word.substring(0, 1).toUpperCase() + word.substring(1);
puncation = "test"; // just a test value
word = word.replace(puncation, "");
//////////////////test to see if works
System.out.println("puncation: " + puncation);
}
//if first word of sentence
if (words.size() == 0) {
//////////////////test to see if works
System.out.println("puncation: " + puncation);
word = word.toLowerCase();
word = word + "" + puncation;
}
newSen.push(word);
}
}
endOfSen = false;
}
}

Java Modulus Operator behaving strangely as an if condition

Hey guys I have the following if condition...
//Add a space if necessary
if (i!=0 && spaceIn>0 && i%spaceIn==0) {
System.out.println("Converted Letter : " + curLtr + " at position " + i + " Needs a space");
curLtr = curLtr + " ";
};
The 1st 2 conditions are always true with the test input i give it.
Whats happening is the modula condition i%spaceIn==0 is not reporting as true when it is.
Example when i is 3 and spaceIn is 3 i%spaceIn=0 if condition works.
When i gets to 6 even tho i can see (from system.out further along) that the answer is 0 its not triggering the if condition.
Sometimes it wasn't doing it when i=12 either!
So weird.
Im printing out the answer to i%spaceIn throughout the loop and even tho the answer is 0 every multiple of 3 comes it sometimes wont trigger the if condition.
Same thing if spaceIn is 5. It skips 10. What ever number it is it seems to just skip sometimes for no reason.
What am i missing?
Use the following code...
You have terminated the if block... It can cause a problem...
if (i!=0 && spaceIn>0 && i%spaceIn==0) {
System.out.println("Converted Letter : " + curLtr + " at position " + i + " Needs a space");
curLtr = curLtr + " "; }
I hope it might work for you as it runs fine on my machine....

Is it possible to exit out of an if-statement and return to an inner for-loop?

Is there a command to exit an if-statement inside of a inner for-loop and have it only go through that inner for-loop?
ex:
for (int i = 0; i < blah.length; i++) {
blh = scan.nextDouble();
blah[i] = blh;
if(scores[i] < MIN || scores[i] > MAX_SCORE) {
errFlag = true;
System.out.println("ERROR: Enter numbers in the range of " +
MIN + "-" + MAX_SCORE + "!");
System.out.print("ERROR: Enter all " + numStudents + " scores again: ");
errFlag = false;
}
}
You may use label block
FOUND: {
for(Type mt: TypeList)
if(condtion(mt))
break FOUND;
// not found code here
}
As per Java Language Specification 14.7
A labeled statement is executed by executing the immediately contained Statement. If the statement is labeled by an Identifier and the contained Statement completes abruptly because of a break with the same Identifier, then the labeled statement completes normally. In all other cases of abrupt completion of the Statement, the labeled statement completes abruptly for the same reason
If you want it to exit the if statement, but stay in the for loop, you can you use the continue statement. It is like a break statement, but it just skips the remaining part of the loop, and continues at the beginning the loop.
Other option:
if you want to skip the further code in the if block but do not intend to break the loop, you can extract that code in a new method and return in between (based on desired condition), that way you can achieve your purpose (if I understand the question correctly)

Categories

Resources