While Loop executing one last time when condition is set to false - java

Task: To check that if a user input string has the same first and last character. If yes or no, output to the screen, if the user enters "done", the loop is exited.
Issue: While loop executes when condition is false
What I've tried: Using different types of loops, doing a loop within the loop to revalidate the code and all together giving up!
import java.util.*;
public class lab_15 {
public static void main(String args[]) {
String userInput = "";
String done = "done";
while (!userInput.equalsIgnoreCase(done))
{
int length;
Scanner sc = new Scanner(System.in);
userInput = sc.next();
length = (int)userInput.length();
if (userInput.charAt(0) == userInput.charAt(userInput.length()-1)) {
System.out.println("The first character equals the second character.");
}
else {
System.out.println("The first and second characters are different.");
}
}
// EXIT LOOP
System.out.println("Thank you for using this software!");
}
}
Inputs
+ bradley
+ hannah
+ done
I am still new to the site and have referred to the t's & c's regarding posts. Please do not negative if you find the question to not be challenging. I am new to programming and hope to progress.
Thank you!!!

This is because you change your userInput immediately once entering the loop. The condition is only checked when you reach the top of the loop, so if you invalidate the condition halfway through, it will continue executing until you reach the top.
The solution is to refactor so that the very last thing that happens is changing your userInput so that the condition is check immediately after the value is changed. (I would also pull the scanner instantiation out of the loop.)
Alternatively you could check your condition inside of the while loop and call break if the userInput has changed to match the terminating condition. The break keyword will force the logic to exit the loop immediately, without evaluating the condition again.

Related

How do I create a while loop in java that will end the game once the two user inputs match?

I have been trying to create a game that asks the user to type in 2 three-letter words; the program is supposed to give clues for how close the words match by splitting them up and stating if the letters come before, or after, each other in the alphabet.
The game is nearly done, but my problem shows up when I try to start a new turn after one guess. I need some kind of while loop, but I've rearranged blocks of the code so many times that I feel like it made the entire thing more convoluted. The prompt for the second user to answer a question, as well as the clue, should be repeated every time the two inputs don't fully match.
Example Output when the two user inputs are cat and fan: after, a, before
The "after" shows that the letter comes after the user's letter in the alphabet, and the "before" shows that the letter comes before the user's letter.
EDIT: I have taken the answers into account as much as I can, thank you so much. So far, I have implemented a do while loop and tried to fix my variables. In the end, I feel that I may have to create an object to be able to recopy the code of the user inputs after a certain conditional statement would be set to false.
My new issues are
1. The compiler cannot find the symbols x1,y1,z1,x2,y2, and z2 whenever I have the user inputs inside the do while loop.
2. If I tried to make a new object, I would be rewriting & rearranging more than what might be necessary.
This is still ongoing, and as I continue to work on it I will keep updating this post.
(EDITED CODE -- I saved the original code which I can send to anyone who would like to see it.)
import java.util.Scanner;
class Main{
public static void main(String[] args) {
System.out.println("Guess The Word\n(requires two players)");
System.out.println("If the letter in each word matches, the letter will be reprinted.");
System.out.println("If the letter guessed doesn't match, either \"before\" or \"after\" will print.");
Scanner in1=new Scanner(System.in);
//Scanner in2=new Scanner(System.in);
try{
boolean correct1=false; boolean correct2=false; boolean correct3=false;
int indication=0;
//asks for user input and stores in substrings
do{
System.out.print("First Player, enter a three letter word: ");
String user1=in1.nextLine();
String x1=user1.substring(0,1);
String y1=user1.substring(1,2);
String z1=user1.substring(2,3);
System.out.print("Second Player, enter a three letter word: ");
String user2=in1.nextLine();
String x2=user2.substring(0,1);
String y2=user2.substring(1,2);
String z2=user2.substring(2,3);
}
while(!correct1||!correct2||!correct3);
//possible end to loop
// if(user1==user2){indication=1;}
// else{indication=0;}
//comparisons of each letter
int comp;
int comp2;
int comp3;
comp=x1.compareTo(x2);
comp2=y1.compareTo(y2);
comp3=z1.compareTo(z2);
//while1=(comp!=0);
//while2=(comp2!=0);
//while3=(comp3!=0);
//if statement 1
if(comp==0){
System.out.print(x1);
correct1=true;
}
else{
// System.out.println(comp);
if(comp>0){
System.out.println("before, ");
}
else{
System.out.print("after, ");
}
}
//if statement 2
if(comp2==0){
System.out.print(y1);
correct2=true;
}
else{
// System.out.println(comp);
if(comp2>0){
System.out.println(", before, ");
}
else{
System.out.print(", after, ");
}
}
//if statement 3
if(comp3==0){
System.out.print(z1);
correct3=true;
}
else{
// System.out.println(comp3);
if(comp3>0){
System.out.println(", before");
}
else{
System.out.print(", after");
}
}
//ignore else{System.out.print("Congratulations!");}
}
finally{in1.close();}/* in2.close();}*/
}
}
Maybe declare 3 booleans (1IsCorrect, 2IsCorrect, 3IsCorrect) set them default to false and in the if(comp/comp1/comp2 == 0) statements after printing the value set the corresponding boolean to true.
then put it in a do while(!1IsCorrect || !2IsCorrect || !3IsCorrect)
declare a variable perhaps for isFirstRun before loop and instantiate it to true at the declaration, then set to false at the very end.
Make an if !isFirstRun statement and add in the code there to ask for the next guess
Hope this works

This do/while loop repeat for no reason, how to fix it?

I am trying to do a false credit card generator. So basically the problem is that when the user says "No" the program continues and shows "Goodbye" but then it starts all over again and can't find why.
I thought of putting all this do/while loop in a for loop so i can put a break at the end but it led to a dead code (which is logical).
public void generateCode() {
char userAnswer;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Put a bin.");
String binGiven = sc.nextLine();
verificationBin();
showCardNumber();
do {
System.out.println("Do u wanna try again ? (Yes/No)");
userAnswer = sc.nextLine().charAt(0);
} while (userAnswer != 'Y' && userAnswer != 'N');
} while (userAnswer == 'Y');
System.out.println("Goodbye");
sc.close();
}
I expected it to stop when the user says No but it starts all over again
According to image you added you are calling the looping code twice. Once from your constructor and once from your main.
This is your code currently:
Generator gen = new Generator();
gen.generateCode();
However, your constructor inside the generator class contains a call to the same method generateCode() shown here:
this.generateCode();
When you use new Generator() this runs the code inside of the constructor as well, so you are running the same code twice. You can confirm this by attempting to run through the program two times and it should stop executing after the second time.
Remove this.generateCode() as this is not really code that should be ran from a constructor.

Using scanner.next() outside loop yields weird results

Recently a friend of mine showed me her code seeking my advice on why it wouldn't work. Her original code was this:
public static void printStem(String word) ...
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
String word = keyboard.next();
printStem(word);
while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
}
This will yield really weird results. It will ask the user twice, then executes printStem twice (which might be expected), and after that goes ahead and always prints only the first entered corpus (word).
Eventually I figured out that it would work as expected when removing the keyboard.next() from outside the loop like so
public static void printStem(String word) ...
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the words: ");
while (keyboard.hasNext())
{
String word = keybord.next();
printStem(word);
}
}
When asked why this would be I had no plausible explanation, as this should behave identical. My best guess is that something must be smelly with hasNext() but I couldn't figure out why exactly. So. What is going on here? Any explanation is appreciated :)
Some explanation about hasNext():
Returns true if this scanner has another token in its input.
This method may block while waiting for input to scan.
The scanner does not advance past any input.
In your first piece of code
you scan for a word: String word = keyboard.next();
You print it: printStem(word);
You enter into a while loop which waits until you give some input: keyboard.hasNext()
In step 3 you take the input but never store it in String word and you print it. Naturally previous value of word will be printed.
Then you do a next read by next().
Explanation for next():
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Hence you get a weird behavior.
This will yield really weird results
Yeah, because the logic is wrong.
You get the input
String word = keyboard.next();
print it
printStem(word);
then print it again, and ask for another word:
while (keyboard.hasNext())
{
printStem(word);
word = keybord.next();
}
So every time you loop you print the word they entered last time, rather than the word they entered this time. You just need to swap the two lines in the while-loop, which then makes the keyboard.next() and printStem(word) outside of the loop body redundant.
as this should behave identical
No it shouldn't. You reversed the order of operations in the while-loop body.

Scanner.next() and hasNext() creating infinite loop when reading from console [duplicate]

I ran into an issue. Below is my code, which asks user for input and prints out what the user inputs one word at a time.
The problem is that the program never ends, and from my limited understanding, it seem to get stuck inside the while loop. Could anyone help me a little?
import java.util.Scanner;
public class Test{
public static void main(String args[]){
System.out.print("Enter your sentence: ");
Scanner sc = new Scanner (System.in);
while (sc.hasNext() == true ) {
String s1 = sc.next();
System.out.println(s1);
}
System.out.println("The loop has been ended"); // This somehow never get printed.
}
}
You keep on getting new a new string and continue the loop if it's not empty. Simply insert a control in the loop for an exit string.
while(!s1.equals("exit") && sc.hasNext()) {
// operate
}
If you want to declare the string inside the loop and not to do the operations in the loop body if the string is "exit":
while(sc.hasNext()) {
String s1 = sc.next();
if(s1.equals("exit")) {
break;
}
//operate
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.
When you use scanner, as mentioned by Alnitak, you only get 'false' for hasNext() when you have a EOF character, basically... You cannot easily send and EOF character using the keyboard, therefore in situations like this, it's common to have a special character or word which you can send to stop execution, for example:
String s1 = sc.next();
if (s1.equals("exit")) {
break;
}
Break will get you out of the loop.
Your condition is right (though you should drop the == true). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt).
it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer.
the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD
If you don't want to use an EOF character for this, you can use StringTokenizer :
import java.util.*;
public class Test{
public static void main(){
Scanner sc = new Scanner (System.in);
System.out.print("Enter your sentence: ");
String s=sc.nextLine();
StringTokenizer st=new StringTokenizer(s," ");//" " is the delimiter here.
while (st.hasMoreTokens() ) {
String s1 = st.nextToken();
System.out.println(s1);
}
System.out.println("The loop has been ended");
}
}
I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.
Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();
Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();
while (input.hasNext()) {
arg.add(input.next().toLowerCase());
}
You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)
Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.
while (sc.hasNext())
{
s1 = sc.next();
System.out.println(s1);
System.out.print("Enter your sentence: ");
}

How to terminate while loop once response is correct?

I'm working on this program that says "get some ice cream"/"put on a jacket" if you type "hot/cold". However, even after you type in hot/cold, the program keeps going in the while loop. How can I make this program keep asking the user for their condition until they correctly respond with one of the two answers, and prevent it from continuously asking for a response even after the user types a correct answer?
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
boolean run = true;
while(run) {
System.out.println("What is your condition: ");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
if(x.equals("hot"))
System.out.println("Get some ice cream");
else if(x.equals("cold"))
System.out.println("Put on a jacket");
else
System.out.print("Try again, what is your condition: ");
}
}
}
your loop iterates as long as run is true. what you need to do is therefore to set run to be false once the input is correct. like this
if(x.equals("hot")){
System.out.println("Get some ice cream");
run = false; // setting run to false to break the loop
}
else if(x.equals("cold")) {
System.out.println("Put on a jacket");
run = false; // setting run to false to break the loop
}
break statement can be used as well.
You may also use do while loop.
In this case, you would have the ability to check your condition against "x" when the loop ends, and hence would not need additional flag.
However, do while loop will run at least once, which I assume you need as per your requirement.

Categories