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 OverflowI 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();
}
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"));
} }
I am having trouble with Java Basics
java - Do While loop with Yes = start again No = exit Program - Stack Overflow
variables - Prompt for user yes or no input in Java - Stack Overflow
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
Videos
- If you don't use Java 7 you can't use switch-strings
Change
while (true)withwhile (yn)so it will stop when he type "no", and changeboolean yn;toboolean 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 letyntrueif yes;falseif no.return default;don't make much sense, if you want to let user repeat in case of error well.. you should do a newwhile (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.
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)...");
}
}
}
}
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();
}
}
I would organize this into a class with methods first. This breaks down each piece of logic and makes it easier to read.
- Start a "play" loop
- Inside the "play" loop, have a "guess" loop
- Store the "continue" state in a known constant
- Only check if they are correct after they made the max number of guesses.
- Seed the
Randomobject 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
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?
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. ");
}
}
}Please, read and follow the Posting rules and also the Code Posting rules.
You keep making low effort, code only posts that are not even properly formatted. This behavior is unacceptable when asking for help.
The Posting Rules mentioned above explain how a proper post needs to be made. The Code posting rules explain how to post code.
Since this is not the first time you do this, consider it a warning. Further similar behavior will lead to consequences such as a permanent or temporary ban from this subreddit.
Where it says '"Do you wish to continue? (yes/no)" @ line #24, when entered "Yes", how can I make it so my program loops the entire program? Help would be highly appreciated, sooner than later if possible :d
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.");
}
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.");
}
String tryAgain = "y";
do
{
// you code
System.out.println("Try again? enter \"y/n\".");
tryAgain = System.in.readLine();
}
while(!tryAgain.equals("n"));
Put your code that computes your magic square in a separate method, and have your input reading code in a while loop, that calls that method until the user presses N, for example.