Java Modulus Operator behaving strangely as an if condition - java

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....

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.

Java not removing specific item from list

I am currently developing a plugin in minecraft spigot. I don't believe this is a spigot problem though, I believe this is a java problem. I have a method called setInjury() in my class that is supposed to make a copy of a list, remove an item from the copy and replace the list with the new one. The weird thing is, this works. For one item in particular though, it just refuses to remove it. It will remove other ones, but not this one. I checked casing and everything. Even the boolean from .remove says it has been removed, yet it just doesn't.
(iStore is a file configuration file while store is my class it's in)
It used to be in an if else statement, but the boolean inside the remove works just the same. The weirdest thing about all of this is it was literally working yesterday.
List<String> sevs = iStore.getStringList(uuid + "." + section);
for(String s : iStore.getStringList(uuid + "." + section)) {
boolean isFracture = s.equals("Fracture") && injury.equals("Broken") ;
if(s.equals(injury)) {
continue;
}
sevs.add("Broken");
sevs.remove(isFracture ? "Fracture" : "Intact");
iStore.set(uuid + "." + section, sevs);
store.saveStore();
}
My other more messy code that does the same thing, to prove that it should remove it:
List<String> sevs = iStore.getStringList(uuid + "." + section);
for(String s : iStore.getStringList(uuid + "." + section)) {
if(sevs.contains(injury)) {
return;
}else if(injury.equals("Broken") && s.equals("Fracture")){
sevs.add("Broken");
sevs.remove("Fracture");
Bukkit.getLogger().info(Boolean.toString(sevs.remove("Fracture"))); //returns true??
iStore.set(uuid + "." + section, sevs);
store.saveStore();
}else{
sevs.add(injury);
sevs.remove("Intact");
iStore.set(uuid + "." + section, sevs);
store.saveStore();
}
List before running code:
rlegstat:
- Cured
- Fracture
//Desired result if injury is equal to broken:
rlegstat:
- Cured
- Broken
//Actual results
rlegstat:
- Cured
- Fracture
- Broken

Java program evaluating twice

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.

java char array to String with spaces

I'm trying something like a crossword puzzle. in a 5 by 5 grid.
25 of them have different letters in them, 1 is the submit button. So whenever i hit the submit button. It will do something like this. str is the word that i retrieve from a text file, and guess is the char array.
if (count == str.length())
{
String a = String.copyValueOf(guess);
a= a.replaceAll("\\s+$", "");
if (str.equals(a))
{
JOptionPane.showMessageDialog(null, "Correct! Well Done!");
score += 10;
totalScore.setText ("Score: " + score);
}
else
JOptionPane.showMessageDialog(null, "Please try again");
the thing is, whether the answer is correct or not, it will only display "please try again". It can work if i change my array size to [5], but if it goes out of bound if i click 6 buttons. Anyone can tell me what's wrong with this?
edit: i added a messageDialog, and it display jump with tons of spaces at the back
JOptionPane.showMessageDialog(null, "|" + a + "|" + str + "|");
Changing it to
a= a.replace(" ", "");
doesn't work too.
Use trim() function. The easiest method to trim spaces from a string.

java statements inside printf and loop conditions

System.out.printf("\n"
+ "\nEnter a question: " + question=stdin.nextLine()
+ "\nEnter a guess: " + Guess=stdin.nextLine());
Produces error "The left-hand side of an assignment must be a variable".
Also,
do
{
...
} while(System.out.printf("\nWould you? "), stdin.nextLine().equalsIgnoreCase("y"))
produces "Syntax error on token ",", . expected"
I want printf to ignore the stuff that doesn't print anything. How to do so?
System.out.printf() does not allow assigning variables. So your attempt on the following code is wrong.
System.out.printf("\n"
+ "\nEnter a question: " + question=stdin.nextLine()
+ "\nEnter a guess: " + Guess=stdin.nextLine());
Try to change the above to multiple lines of code, after declaring all properly.
question=stdin.nextLine();
Guess=stdin.nextLine();
System.out.printf("\n"
+ "\nEnter a question: " + question
+ "\nEnter a guess: " + Guess);
The following do .. while() statement also have the same problem.
do
{
...
} while(System.out.printf("\nWould you? "), stdin.nextLine().equalsIgnoreCase("y"))
try the following
String answer = "n";
do
{
...
System.out.printf("\nWould you? ");
answer = <-- Get the user input using System.in -->;
} while (!answer.equalsIgnoreCase("y"))
you look like having syntax problem and following C++ way. Try to get hands on some java basics books and you are all set to go ..
Happy coding
Either question or Guess is not variable. Perhaps Guess is a class, not a variable.
The assignment is not automatically what gets assigned:
question = stdin.nextLine ();
assigns the result of stdin.nextLine () to question, but the result of the assignment is void, not question.
So your only solution is to work in 2 steps: do the assignment, and then, since nextLine has side effects, print the assigned values with println.

Categories

Resources