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
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
While Loop not working for a yes or no question
You seem to try to compare String values with == or !=. This approach does not work in Java, since String is an object data type and these can only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase(). See Help on how to compare String values in our wiki. Your post is still visible. There is no action you need to take. Still, it would be nice courtesy, even though our rules state to not delete posts, to delete your post if my assumption was correct. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
3
1
May 28, 2018
Trouble creating a java loop to loop based on yes or no input - Stack Overflow
I just need it so that after it computes, it prompts the user to input "y" or "Y" for the program to loop with new values and "n" or "N" to end the program. ... 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!
🌐
YouTube
youtube.com › watch
Java Programming Tutorial 23 Do You Want To Continue Yes or No in Java - YouTube
Learn Prompt Programming in Java. Do You Want To Continue Yes or No in Java. Program shows how to repeat the execution of a program using do while loop in ...
Published   April 27, 2015
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)...");
      }
    }
  }
}
🌐
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
May 28, 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?

🌐
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.
Find elsewhere
🌐
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(); ...
🌐
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).
🌐
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....
🌐
How To Learn Java
howtolearnjava.com › home › how to loop a java program with a prompt
How to Loop a Java Program With A Prompt - How To Learn Java
April 22, 2025 - javaimport java.util.Scanner; // Required for user input public class RetryLoop { public static void main(String[] args) { // Step 1: Create input scanner Scanner scanner = new Scanner(System.in); boolean retry; // Step 2: Create the retry loop do { // YOUR CODE GOES HERE - REPLACE THIS LINE! System.out.println("Running program..."); // Step 3: Ask to continue System.out.print("Try again? (yes/no): "); String input = scanner.nextLine().trim().toLowerCase(); retry = input.equals("yes"); } while (retry); // Step 4: Repeat if user says "yes" // Step 5: Clean up scanner.close(); } } Key Features: ▸ Works for basic programs ▸ Easy to understand ▸ Requires no extra tools ·
🌐
Team Treehouse
teamtreehouse.com › community › yes-or-no-loop
yes or no loop (Example) | Treehouse Community
January 13, 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.");
}
🌐
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")); ... Nope, you need 2 loops: first is like what you have now, ...
🌐
Whirlpool
forums.whirlpool.net.au › programming › java › while loop with yes or no boolean value
While loop with yes or no Boolean Value - Java
April 26, 2008 - What I need is While loop with yes or no to continue.. Basically program writes keyboard entry commands in to the external file called myfile.txt. All I want if user want to enter more information I want to ask them at the end of program Would you like to Continue type question and put this in to the form of Loop. Can you Guys help me please? Regards, Gokhan ... um.. not sure if this is what you need but something like this? boolean continue = true; while (continue) { .. do your stuff, read characters write to file ..
🌐
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...