I updated your code a bit. You are now able to Type 15F, 15C, ... (without whitespace) to convert. After this you will be asked if you want to continue.

public static void main(String[] args) {
        double deg = 0;
        Scanner input = new Scanner(System.in);

        do {
            System.out
                    .println("Enter a number and F to convert from degF to degC or C to convert to degC to degF");
            String text = input.next().toUpperCase();

            try {
                deg = Double.parseDouble(text.substring(0, text.length() - 1));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            if (text.endsWith("C")) {
                double cTemp = (deg - 32) * 5.0 / 9.0;
                System.out.printf("%f degC converted to degF is %.2f%n", deg, cTemp);
                ;
            } else if (text.endsWith("F")) {
                double fTemp = (deg * 9 / 5) + 32;
                System.out.printf("%f degF converted to degC is %.2f%n", deg, fTemp);
                continue;
            } else {
                System.out
                        .println("That character does not correspond to a valid unit of measure ");
            }
            System.out.println("Type YES to continue");
        } while (input.next().equalsIgnoreCase("YES"));
        input.close();

    }
Answer from nidomiro on Stack Overflow
Top answer
1 of 5
2

I updated your code a bit. You are now able to Type 15F, 15C, ... (without whitespace) to convert. After this you will be asked if you want to continue.

public static void main(String[] args) {
        double deg = 0;
        Scanner input = new Scanner(System.in);

        do {
            System.out
                    .println("Enter a number and F to convert from degF to degC or C to convert to degC to degF");
            String text = input.next().toUpperCase();

            try {
                deg = Double.parseDouble(text.substring(0, text.length() - 1));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            if (text.endsWith("C")) {
                double cTemp = (deg - 32) * 5.0 / 9.0;
                System.out.printf("%f degC converted to degF is %.2f%n", deg, cTemp);
                ;
            } else if (text.endsWith("F")) {
                double fTemp = (deg * 9 / 5) + 32;
                System.out.printf("%f degF converted to degC is %.2f%n", deg, fTemp);
                continue;
            } else {
                System.out
                        .println("That character does not correspond to a valid unit of measure ");
            }
            System.out.println("Type YES to continue");
        } while (input.next().equalsIgnoreCase("YES"));
        input.close();

    }
2 of 5
1

You are taking the USER input only one time so i m not sure why you are using do-while loop.Also if you are trying to iterate on the basis on YES\NO then add the inputs in the do loop and add one for input about YES/NO and add this check in while.

Use below code :

public class Temperature
 {
 public static void main(String[] args){

    Scanner input = new Scanner (System.in);
    double deg;
    char dg;
    String con;

    do{
         System.out.println("Enter a number, a space and F to convert from degF to degC and C to convert to degC to degF and YES to continue");
        deg= input.nextDouble();
        String letter = input.next().toUpperCase();
        dg = letter.charAt(0);
        con = input.next();

        if( dg == 'C'){
            double cTemp= (deg-32)*5.0/9.0;
            System.out.printf("%f degC converted to degF is %.2f%n",deg, cTemp );;
        }
        else if(dg == 'F'){
            double fTemp = (deg*9/5) + 32;
            System.out.printf("%f degF converted to degC is %.2f%n",deg, fTemp );
            continue;
        }
        else{
            System.out.println("That character does not correspond to a valid unit of measure ");
            break;
        }
    }while(con.equalsIgnoreCase("YES"));
} }
Discussions

I am having trouble with Java Basics
Joey Sadowski is having issues with: Now continually prompt the user in a do while loop. The loop should continue running as long as the response is No. Don't forget to declare resp... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
2
June 5, 2015
java - Do While loop with Yes = start again No = exit Program - Stack Overflow
I have to add a do-while loop to my project so after the program iterates it says: "You want a run this program again? (Yes or No)" If user inputs are Yes or YEs or YES or yEs or yES or yeS It ru... More on stackoverflow.com
๐ŸŒ stackoverflow.com
September 26, 2017
variables - Prompt for user yes or no input in Java - Stack Overflow
how to prompt user to loop the code yes to loop no to exit and wrong input print wrong input and go back to statement ie. "do you want to enter another name:" import java.util.Scanner; public class More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How do I ask the user to "play again" and rerun the do while loop with a simple yes or no question? - Stack Overflow
So I added the yes or no statement prints out but it doesn't allow the user to type it in. How do I fix that and can I nest a while loop inside a do-while loop? import java.util.Scanner; import java. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 68041198 โ€บ do-while-loop-with-a-yes-no-user-prompt
java - do while loop with a Yes/No user prompt - Stack Overflow
Relatedly, equals("Y") is not the same as not equals("N"). (Consider "Hello" ... or "n". They are neither "Y" or "N".) So if you really want to stop the loop when the user types N, then the loop termination condition should be:
Top answer
1 of 2
4
Hi Joey, The do-while loop is a post-test loop. A post-test loop runs the code inside the loop body at least one time then evaluates the looping condition after the code in the loop body is ran. So, there is no need for an if-statement in this exercise. ```java //Declare a String variable named response, then initialize it using double quotes String response; // The do while loop keeps asking the same question until "yes" is entered //So we want to keep repeating when "no" is typed // Exit the loop when "yes" is entered //task 2 do{ response = console.readLine("Do you understand do while loops?"); // "yes" or "no" is stored in the response variable // when someone types "no" the loop repeats // when someone types "yes" the loop is exited }while(response.equalsIgnoreCase("no")); ``` If you have any other questions feel free to ask! Hope this helps!
2 of 2
3
Hola, You are close, String = response is the same as saying String the object is equal to response. That can't happen. to define a variable without giving it a value. It's as follows: ```java String response; ``` The best part of this is that because it's defined at the class level. Scope isn't a worry and you can change the value through out the class. Next, you are assuming that if I don't say No, that I am going to say yes. What if I said maybe? Then the program would fail. I didn't choose yes or no. ```java do{ response = console.readLine("Do you understand do while loops?"); }while(response.equalsIgnoreCase("no")); if{ response = "yes" console.exit; } ``` See, you have a while loop that runs 1 time no matter what. But if I choose maybe, it breaks. If I say anything other than No. It leaves the do while checks if it's yes and exits. But if it's not yes what then? ```java String response; do{ response = console.readLine("Do you understand do while loops?"); if (response.equals("No")) { console.printf("Because you said %s, you passed the test!", response); } }while(response.equals("No")); ``` Now see above. I define the variable above the do while. Now, I ask a question. IF the question comes back as No, then I print awesome you passed the test. Then it goes down to the while, and says oh sweet. It's No so it quites. Now if I typed yes, maybe, food, dog. Wouldn't matter. It would just keep going until it got No. There are several ways you could do it, you could of defined a boolean and set it in the if statement or not. But hey, less is more and do what you know. Let me know if that helps. Thanks!
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 46417187 โ€บ do-while-loop-with-yes-start-again-no-exit-program
java - Do While loop with Yes = start again No = exit Program - Stack Overflow
September 26, 2017 - In that case the program should ask for every String not equals to "no", and therefore anything else "no" will repeat the cycle: while(!reader.nextLine().toLowerCase().equals("no")); 2017-09-26T03:36:22.263Z+00:00 ... Nope, you need 2 loops: first ...
Top answer
1 of 5
5
  1. If you don't use Java 7 you can't use switch-strings
  2. Change while (true) with while (yn) so it will stop when he type "no", and change boolean yn; to boolean yn = true; And change the rules inside the cases too.

    case "yes":
         yn = false;
         break;
    case "no": 
         yn = true;
         break;
    

    yn = true; if "yes";

    yn = false; if "no";

    You could change the condition inside the while, with while (!yn) but is more intuitive to let yn true if yes; false if no.

  3. return default; don't make much sense, if you want to let user repeat in case of error well.. you should do a new while (true) to repeat until he writes a correct one. I would write another method.

This is how you could do it

Scanner kbd = new Scanner (System.in);

String decision;

boolean yn = true;
while(yn)
{
    System.out.println("please enter your name");
    String name = kbd.nextLine();

    System.out.println("you entered the name" + name );

    System.out.println("enter another name : yes or no");
    decision = kbd.nextLine();


    switch(decision)
    {
        case "yes":
            yn = true;
            break;

        case "no":
            yn = false;
            break;

        default:
            System.out.println("please enter again ");
            boolean repeat = true;

            while (repeat)
            {
                System.out.println("enter another name : yes or no");
                decision = kbd.nextLine();

                switch (decision)
                {
                    case "yes":
                        yn = true;
                        repeat = false;
                        break;

                    case "no":
                        yn = repeat = false;
                        break;
                    default:
                        repeat = true;
                }
            }
            break;
    }
}

Yes it will repeat decision code, but how it is created i think it is the only way to do it.

2 of 5
4

Yes, but you'd want while(yn), not while(true), which goes on forever. The break only breaks from the switch statement.


Alright, try this:

import java.util.Scanner;

public static void main(String args[]){
  Scanner s = new Scanner(System.in);

  boolean checking = true, valid = true;
  String[] names = new String[50];
  int i = 0;

  while(checking){
    System.out.println("Enter name...");
    me = s.nextLine();
    System.out.println("You entered " + me + ".");
    while(valid){
      System.out.println("Enter another? y/n");
      you = s.nextLine();
      if(you.equals("n")){
        valid = false;
        checking = false;
      }else if you.equals("y")){
        names[i] = you;
        i++;
        valid = false;
      }else{
        System.out.println("Sorry, try again (y/n)...");
      }
    }
  }
}
Top answer
1 of 2
1

Well, as I look to your looping logic it could be maintained and working as charm, you just need to move the initialization steps from the outside, to the inside do-while loop, in the beginning.

That way, at each start of the game, everything will work.

Also you're forgetting to go to next line before reading the user choice of yes/no, as you were reading just ints, at the end your a line ahead of the line containing the verdict yes/no

I tried this code in an online compiler, and it's working :

import java.util.Scanner;
import java.util.Random;

public class Main{

     public static void main(String []args){

        Random random = new Random();
        Scanner input = new Scanner(System.in);
        final int MAX = 100;

        System.out.println("Guess a number between 1 and " + MAX + ": ");
        String cont = new String();
        do {
            System.out.println("Let's play");
            //Initializations here
            int answer = random.nextInt(MAX) + 1;
            int guess = -1;
            int numberOfGuesses = 0;


            while (guess != answer) {
                numberOfGuesses++;
                guess = input.nextInt();

                if (guess == 101) {
                    break;
                } else if (guess > answer) {
                    System.out.println("Too High");
                    System.out.println("\nGuess again ");
                } else if (guess < answer) {
                    System.out.println("Too Low");
                    System.out.println("\nGuess again: ");
                } else {
                    System.out.println("Correct! The number was " + answer + ".");
                    System.out.println("It took you " + numberOfGuesses + " guesses.");
                }
            }

            System.out.println("\nWould you like to play again (yes/no)?");
            input.nextLine();//You have to go to the next line...
            cont = input.nextLine();
        } while (cont.equals("yes"));
        System.out.println("\nThanks for playing !");
        input.close();
     }
}
2 of 2
0

I would organize this into a class with methods first. This breaks down each piece of logic and makes it easier to read.

  1. Start a "play" loop
  2. Inside the "play" loop, have a "guess" loop
  3. Store the "continue" state in a known constant
  4. Only check if they are correct after they made the max number of guesses.
  5. Seed the Random object with the current system time

Also, I added a DEBUG flag to display the answer.

Update: The program is ignoring or not even asking for your "yes" input, because you were previously asking it for integers. You will need to clear/flush/reset the scanner's buffer by calling nextLine. Switching from integer to string leaves some data in the buffer. So your program will use the left-over character data in the buffer before it prompts you for your input.

import java.util.Scanner;
import java.util.Random;

public class HiLo implements Runnable {
    private static boolean DEBUG = true; // Disable to not show the answer...
    private static final int MAX_NUMBER = 100;
    private static final int MAX_GUESSES = 5;
    private static final String YES = "YES";

    private final Random rand;

    public HiLo() {
        this.rand = new Random(System.currentTimeMillis());
    }

    public static void main(String[] args) {
        new Thread(new HiLo()).start();
    }

    @Override
    public void run() {
        Scanner scan = new Scanner(System.in);
        String cont = "";
        do {
            play(scan);
            System.out.print("\nWould you like to play again (yes/no)? ");
            cont = scan.nextLine();
            System.out.println();
        } while (cont.equalsIgnoreCase(YES));
        scan.close();
    }

    public void play(Scanner scan) {
        boolean correct = false;
        int numberOfGuesses = 0;
        int answer = rand.nextInt(MAX_NUMBER) + 1;

        if (DEBUG) System.out.printf("The answer is: %d%n", answer);

        System.out.printf("Guess a number between 1 and %d%n", MAX_NUMBER);

        while (numberOfGuesses < MAX_GUESSES && !correct) {
            numberOfGuesses++;
            correct = makeGuess(scan, answer, numberOfGuesses);
        }

        if (numberOfGuesses <= MAX_GUESSES && correct) {
            System.out.printf("Correct! The number was %d. It took you %d guesses.%n", answer, numberOfGuesses);
        } else {
            System.out.printf("Sorry, but you did not guess: %d", answer);
        }
        scan.nextLine(); // Reset...
    }

    public boolean makeGuess(Scanner scan, int answer, int currentGuesses) {
        System.out.print("Guess: ");
        int guess = scan.nextInt();

        if (guess == answer) {
            return true;
        }

        if (currentGuesses < MAX_GUESSES) {
            if (guess > answer) {
                System.out.print("Too High, ");
            } else {
                System.out.print("Too Low, ");
            }
        }

        return false;
    }
}

Sample Output

The answer is: 64
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 75
Too High, Guess: 60
Too Low, Guess: 65
Too High, Guess: 64
Correct! The number was 64. It took you 5 guesses.

Would you like to play again (yes/no)? yes

The answer is: 88
Guess a number between 1 and 100
Guess: 50
Too Low, Guess: 90
Too High, Guess: 80
Too Low, Guess: 85
Too Low, Guess: 87
Sorry, but you did not guess: 88

Would you like to play again (yes/no)? no
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ while loop not working for a yes or no question
r/javahelp on Reddit: While Loop not working for a yes or no question
November 5, 2018 -

Creating a tax calculator that lets users set their own custom tax rate if they wish or it will set to a default rate, but my while loop doesn't work.

System.out.println("Would you like to set a custom Tax Rate?");
		answer = ScanUserInput.nextLine();
		while (answer != "Yes" && answer != "No") {
			System.out.println("Invalid input, please try again");
		

		if (answer.equals("Yes")) {

			System.out.println("Please enter your custom Tax Rate");
			defaultTaxRate = ScanUserInput.nextDouble();
		} else {

			System.out.printf("Default Tax Rate of  " + defaultTaxRate + " will be applied.");

If the user enters something that is not "Yes" or "No" it gives the message "Invalid input, please try again" but keeps producing the message over and over again on the console.

How do I get it to display only once?

Also if the user answers yes or no, it still gives the message, however only once, and then goes on to display the corresponding message for either yes or no, any tips?

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63929190
Trouble creating a java loop to loop based on yes or no input - Stack Overflow
String yn = "y"; while (yn.equalsIgnoreCase("y")) { // all your code up to the end of all your IF statements... // WHILE loop for the "Would you like to continue" prompt... yn = ""; while (yn.isEmpty()) { System.out.println(); System.out.println(); ...
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ prompt-for-user-yes-or-no-input-in-java
Java: Java Implementation for Obtaining User Input as Yes or No
March 30, 2023 - Instead of utilizing "break" and "while(true)", it is advised to implement while(!yn) and set yn to false when the user inputs "yes". Java - Write an input validation loop that asks the user to, !input.equals ("Yes") && !input.equals ("No") That should answer your question about why your code works.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ adding a continue (yes/no) string prompt to program
r/javahelp on Reddit: Adding a Continue (yes/no) string prompt to program
September 16, 2016 -

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;

{

public static void main(String args[]) throws ParseException{ Scanner input = new Scanner(System.in); System.out.print("Enter first time (hh:mm a/pm): "); String time = input.nextLine(); System.out.println(); System.out.print("Enter second time (hh:mm a/pm): "); String time2 = input.nextLine(); System.out.println(); DateFormat simpleDF = new SimpleDateFormat ("hh:mm aa"); //specifying time format using time format syntax Date date1 = simpleDF.parse(time); Date date2 = simpleDF.parse(time2);

 System.out.println("Time is: " + simpleDF.format(date1));
System.out.println("Time is: " + simpleDF.format(date2));
if(date1.after(date2)){ //creating conditions for output
 long diffMs = date1.getTime() - date2.getTime();
 long diffSec = diffMs / 1000;
 long min = diffSec / 60;
 long sec = diffSec % 60;
 System.out.println("The difference is "+min+" minutes.");
}

if(date1.before(date2)){
 long diffMs = date2.getTime() - date1.getTime();
 long diffSec = diffMs / 1000;
 long min = diffSec / 60;
 long sec = diffSec % 60;
 System.out.println("The difference is "+min+" minutes.");
}

if(date1.equals(date2)){
 System.out.println("There is no difference.");
}
// if(!(cont.equalsIgnoreCase("Yes") || (cont.equalsIgnoreCase("No")))){
System.out.println();    
System.out.println("Do you wish to continue? (Yes/No) ");
String cont = input.next();

if(!(cont.equalsIgnoreCase("Yes") || (cont.equalsIgnoreCase("No")))){
    System.out.println("Invalid option.");
    System.out.println();
    System.out.println("Enter valid option: (Yes/No)");
    cont = input.next();
}
if(cont.equalsIgnoreCase("Yes")){
     
}
if(cont.equalsIgnoreCase("No")){
    System.out.println("Thanks, that is all. ");
}

        }
}
๐ŸŒ
BeginwithJava
beginwithjava.com โ€บ java โ€บ loops โ€บ do-while-loop.html
Do While Loop in Java
Enter integer: 6 Enter Y for yes ... 4 Enter Y for yes or N for no: n Sum of the integers: 18 ยท Following example uses a do while loop to implement the Guessing the Number game. The program gives as many tries as the user needs to guess the number. import java.util.Scanner; // ...
๐ŸŒ
Blogger
safdardogar.blogspot.com โ€บ 2020 โ€บ 05 โ€บ do-you-want-to-continue-yes-or-no-in-java.html
Do You Want To Continue Yes or No in Java. User Want to Continue Program in Java - Safdar Dogar
May 8, 2020 - Do You Want To Continue Yes or No in Java. User Want to Continue Program in Java ยท User Need to Add Loop So it Asks To User Do You Want to Continue Program Again and again. When User Test Program Then User want to Test Another Task. Program ask the user to Do You Want to Continue (Y/N).
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ yes-or-no-loop
yes or no loop (Example) | Treehouse Community
February 24, 2018 - Looping until the value passes ยท Example.java ยท // I have initialized a java.io.Console for you. It is in a variable named console. String response; boolean yesNo; do { response = console.readLine("Do you understand do while loops?"); yesNo = if (yesNo) { console.printf("Please try again "); } } while (yesNo); 243,861 Points ยท
Top answer
1 of 2
2

Your code only checks the first character of the input, so it's no wonder words starting with y or n are considered valid. You might want to compare the entire String :

String response = keyboard.next();
while (!response.equalsIgnoreCase("y") && !response.equalsIgnoreCase("n")) {
  System.out.println("\nInvalid response. Try again.");
  response = keyboard.next();
} 
if (response.equalsIgnoreCase("n")) {
  System.out.println("\nCome back next time, " + customerName + ".");
} else {
  System.out.println("\nGreat! Let's get started.");
}
2 of 2
0

The issue is that you are checking only the first letter of the read string:

char response = keyboard.next().charAt(0)

You should read the whole string:

String response = keyboard.next()

And use it in the comparison. In order to ensure that also 'Y' and 'N' are considered valid, you can use the String.equalsIgnoreCase(String):

while (!"Y".equalsIgnoreCase(response) && "N".equalsIgnoreCase(response))

System.out.println("\nWould you like to order some coffee, " + customerName + "? (y/n)");

So, wrapping all together this would look like this:

String response = keyboard.next();

while (!"Y".equalsIgnoreCase(response) && "N".equalsIgnoreCase(response)) {
   System.out.println("\nInvalid response. Try again.");
   response = keyboard.next();
} 

if ("N".equalsIgnoreCase(response)) {
   System.out.println("\nCome back next time, " + customerName + ".");
} else if ("Y".equalsIgnoreCase(response)) {
   System.out.println("\nGreat! Let's get started.");
}
๐ŸŒ
HWS Math
math.hws.edu โ€บ javanotes โ€บ c3 โ€บ s3.html
Javanotes 9, Section 3.3 -- The while and do..while Statements
The do loop makes sense here instead ... the end of the loop wouldn't even make sense at the beginning: do { Play a Game Ask user if he wants to play another game Read the user's response } while ( the user's response is yes ); Let's convert this into proper Java code....
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 32894774 โ€บ how-do-i-make-my-do-while-loop-with-user-prompt-work
java - How do I make my do while loop with user prompt work? - Stack Overflow
Try again"; System.out.println("You guessed " + NumberUser + "." + Guess); if (NumberGame == NumberUser) Bonus = "Now that you've won, wanna play again? Type Y to play again or any other key to exit:"; else Bonus = " "; System.out.println(Bonus); BonusResponse = (char) System.in.read(); } while (BonusResponse == 'Y' || BonusResponse == 'y'); } } ... You can use Scanner class as seen on this answer or BufferedReader as seen on this answer. ... import java.io.BufferedReader; import java.io.InputStreamReader; class Areas { public static void main(String args[]){ float PI = 3.1416f; int r=0; String rad; //We're going to read all user's text into a String and we try to convert it later BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
๐ŸŒ
Quora
quora.com โ€บ How-can-you-do-a-do-while-loops-in-Java-with-user-input-and-statement
How to do a do while loops in Java with user input and statement - Quora
Answer (1 of 3): import java.io.*; class Sum { static void acc()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter numbers... press 0 for results"); int x, sum1=0, sum2=0; do { x=Integer.parseInt(br.readLine()); if(x%2...