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.
Related
Scanner sal = new Scanner(System.in);
System.out.print("Enter first_salary: ");
int Salary1 = sal.nextInt();
System.out.print("Enter second_salary : ");
int Salary2 = sal.nextInt();
System.out.print("Combined Salary is " + Salary1 + Salary2);
I am trying to get user input twice, and then print the sum. Instead, the output is concatenating the numbers instead of actually adding them.
Because the + operator associates left to right. Your argument is equivalent to the explicit
(("Combined Salary is " + Salary1) + Salary2)
Since ("Combined Salary is " + Salary1) results in a string, you will concatenate strings. To group differently, adjust the order of operations with parentheses:
System.out.print("Combined Salary is " + (Salary1 + Salary2));
As to why this happens, #MadPhysicist's answer covers that.
As to how to avoid this you can either use parentheses as they said or you can use string formatting, like this:
System.out.println("Combined Salary is %d".formatted(Salary1 + Salary2));
String has had the formatted method since Java 15. If you're stuck with an older version you can use the static format method instead:
System.out.println(String.format("Combined Salary is %d", Salary1 + Salary2));
I don't how to title this question more succinctly. Basically, I want to know how to run a for-loop while each loop invokes a TimeUnit.SECONDS.sleep method and add values to the end of a list that that loop is going through if there is user input.
Here is the relevant code:
Scanner input = new Scanner(System.in);
for (int i = 0; i < printQueue.size(); i++)
{
System.out.println("Printing " + i + " of " + printQueue.size()
+ "\n" + printQueue.get(i).getJobTime()
+ " seconds remaining."
+ "\nPlease press \"Enter\" to submit a new print"
+ " job.");
TimeUnit.SECONDS.sleep(printQueue.get(i).getJobTime());
if (input.hasNextLine())
{
input.nextLine();
int printTime = jobGen.nextInt(10);
PrintJob job = new PrintJob();
job.setJobNum(i);
job.setJobTime(printTime);
printQueue.add(job);
}
}
System.out.println(
"Printed " + printQueue.size() + " of " + printQueue.size());
}
Where printQueue is a LinkedList of different PrintJobs which each have a jobNum and more importantly a jobTime. If the user has pressed the enter key during any individual loop, a new PrintJob is automatically generated and added to the end of printQueue.
What happens now instead, is that the program just runs and never terminates unless I press the enter key. I know that hasNextLine and hasNext may block to scan the specified item, but I don't know how else to implement something like this.
Thank you.
Scanner.hasNextLine() blocks waiting for input until either a line is available or the end of the input is reached. As a result, you can't use it synchronously to check whether input is available. As #Abion47 suggested, you should move this input processing to a separate thread.
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....
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.
I made a simple address book program using an Arraylist (program does not save entries after termination) and when I search the entries for an entry that was not the first one my error messages comes up with the entry information. I understand that this is happening because of the if condition used and the the error being an else. But I do not know how to make the program work another way. I want to be able search the entries for a specific name (String) and then display that persons contact info and if that name was not entered display "That person is not listed try another". I am very new to programming and have a very limited knowledge and I know my code looks bad right now but I would like to make it work correctly before making it look good.
while(!search){
if(listSize == 0){
break;//does not allow search if no names have been entered.
}
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
for(AddressBook a: myBook){
if(searchName.compareTo("Q") == 0){
search = true;//allows user to exit search
}
else if(a.getName().compareTo(searchName) == 0){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
search = true;
break;
}
else
System.out.println("That name is not listed please try another");
}
}
This is the search portion of my code, the problem I am having is with the last else if / else. I know that when I search for a name and it doesn't come up in the first element the program goes to the else because the else if condition is false and that is what I need to fix.
You made a logic error in your for statement.
First, you should check for "Q" letter entered only once (not in for statement).
Then you should check for existence of one of the names every iteration of the for, and then (if all items of myBook collection doesn't appears your search condition(equals to searchName), you should show the error message. So, improved code version looks like this:
while(!search){
if(listSize == 0){
break;//does not allow search if no names have been entered.
}
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
if(searchName.compareTo("Q") == 0){
search = true;//allows user to exit search
break; //exit "while" iteration
}
boolean found = false;
for(AddressBook a: myBook){
if(a.getName().compareTo(searchName) == 0){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
search = true;
found = true;
}
}
if(found == false)
System.out.println("That name is not listed please try another");
}
Did you try something like this:
System.out.print("Please enter the first name to search for or q to quit: ");
String searchName = in.next().trim().toUpperCase();
if (searchName.equals("Q") == false)
{
boolean found = false;
for(AddressBook a: myBook){
if(a.getName().toUpperCase().equals(searchName)){
System.out.println("that contact info is: ");
System.out.println("name: " + a.getFullName());
System.out.println("phone number: " + a.getPhoneNumber());
System.out.println("email: " + a.getEmail());
System.out.println("address: " + a.getAddress());
found = true;
break;
}
if(found == false)
{
System.out.println("Item Not Found!");
}
}
P.S. I think you should be using a HashMap since it is far more efficient if you just want to store and retrieve specific strings.
For a short tutorial, please follow this link.
Here is the flow you have now:
1. Read in the requested name to search for
2. Get the first element in the list. Put it in a.
a. Did the user enter Q? Then eventually exit the loop.
b. Does the first element match? If so, print info.
c. Otherwise, print The name is not listed. Try again...
What you want is
1. Read request
2. If request is Q, quit.
3. If request is not Q then loop through the list
a. If an element matches, set flag saying we found a match.
4. After the loop, check the flag to see if a match was found. If it was, print the info
5. If a match wasn't found, print Try again.
The long and short is, you will need to move some of your code out of the loop. I could write the code for you, but I'm sure you can get it. I will monitor this if you have more questions so I can help!
First of all, I would not use ArrayList - if you're going to search by name all the time, I would make it a Map with fullName as the key.
On the second case, why are you checking if searchNAme is "Q" in the Addressbook loop? You should do that instead of the loop.