How to convert a do while loop to a while loop - java

How do I convert my do-while loop to a while loop?
int numAttempts = 0;
do
{
System.out.println("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen"))
{
notPesoOrYen = false;
}
else if (numAttempts < 2)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
numAttempts++;
} while(notPesoOrYen==true && numAttempts < 3);
I tried to do while(notPesoOrYen==true && numAttempts < 3) then the statement but it did not work.
MY FULL CODE
package currencyconverter;
import java.util.Scanner;
import java.text.NumberFormat;
public class CurrencyConverter
{
public static void main(String[] args)
{
Scanner readKeyboard = new Scanner(System.in);
double doubleUsersCaptial;
boolean notPesoOrYen=true;
String pesoOrYen;
double usersConvertedCapital;
boolean userInputToRunProgramAgain=true;
final double US_DOLLAR_TO_PESO = 13.14;
final double US_DOLLAR_TO_YEN = 106.02;
do
{
System.out.println ("How much money in US dollars do you have?");
String usersCaptial = readKeyboard.nextLine();
doubleUsersCaptial = Double.parseDouble(usersCaptial);
int numAttempts = 0;
do
{
System.out.println ("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if(pesoOrYen.equalsIgnoreCase("Peso")||pesoOrYen.equalsIgnoreCase("Yen"))
{
notPesoOrYen = false;
}
else if (numAttempts < 2)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
numAttempts++;
}while(notPesoOrYen==true && numAttempts < 3);
if(numAttempts==3)
{
System.out.println("Sorry, but '"+pesoOrYen+"' is not a valid currency type.");
System.out.println("You entered the wrong currency type too many times\nGood Bye");
System.exit(0);
}
if (pesoOrYen.equalsIgnoreCase("Peso"))
{
usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_PESO;
}
else
{
usersConvertedCapital = doubleUsersCaptial*US_DOLLAR_TO_YEN;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String formatUsersCaptial = formatter.format(doubleUsersCaptial);
String formatUsersConvertedCapital = formatter.format(usersConvertedCapital);
System.out.println(formatUsersCaptial+"US Dollars = "
+formatUsersConvertedCapital+" "+pesoOrYen);
System.out.println("Would you like to run the Program Again?(enter 'yes' or 'no')");
String runProgramAgain = readKeyboard.nextLine();
if (runProgramAgain.equalsIgnoreCase("yes"))
{
userInputToRunProgramAgain = true;
}
else if (runProgramAgain.equalsIgnoreCase("no"))
{
System.out.println("Goood Bye");
System.exit(0);
}
else
{
System.out.println ("You entered something other than 'yes' or 'no'\n"
+"Good Bye");
System.exit(0);
}
}while (userInputToRunProgramAgain==true);
}
}

while and do... while are almost the same, do... while simply performs an iteration before evaluating for the first time the exit condition, whereas while evaluates it even for the first iteration (so eventually the body of a while loop can never be reacher whereas a do... while body will always be executed at least once).
Your code snippet is not complete but I guess you didn't initialized notPesoOrYen to true before the loop and that's why it is not working. Finally, don't write while(notPesoOrYen==true && numAttempts < 3) but while(notPesoOrYen && numAttempts < 3), the == true comparison is unnecessary.

Initialise your boolean variable outside while loop:
int numAttempts = 0;
boolean notPesoOrYen=true;
while (notPesoOrYen && numAttempts < 3) {
System.out.println("Do you want to convert to Peso or Yen?");
pesoOrYen = readKeyboard.nextLine();
if (pesoOrYen.equalsIgnoreCase("Peso") || pesoOrYen.equalsIgnoreCase("Yen")) {
notPesoOrYen = false;
} else if (numAttempts < 2) {
System.out.println("Sorry, but '" + pesoOrYen + "' is not a valid currency type. Try again:");
notPesoOrYen = true;
}
++numAttempts;
};

Related

Is there a way to fix this Method to return the value?

I built a Method that would allow me to send a double and return back as a char but the only thing that seems to register is my 'c' return. What am I doing wrong?
public static void playOneGame () {
double max = 100;
double min = 1;
char userInput;
double guess = 50;
userInput = getUserResponseToGuess(guess);
while(userInput !='c') {
if(userInput == 'h') {
min = guess;
guess= midPoint(min,max);
}
else if(userInput== 'l')
{
max = guess;
guess = midPoint(min,max);
}
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
}
while (userInput == 'c')
{
shouldPlayAgain();
public static char getUserResponseToGuess(double guess)
{
char input;
System.out.println("Is it: "+ (int)guess + "(h/l/c)");
input = scnr.next().charAt(0);
return input;
Ok I figured it out and I guess I will answer my own question for anyone who may see this and has a similar question. I initialized the original input but that wont loop back again, so I had to initialize another userInput at the bottom of the loop Ex:
userInput = getUserResponseToGuess(guess);
while(userInput !='c') {
if(userInput == 'h') {
min = guess;
guess= midPoint(min,max);
}
else if(userInput== 'l')
{
max = guess;
guess = midPoint(min,max);
}
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
**userInput = getUserResponseToGuess(guess);**
}
It is right after the else Statement from the initial while loop.
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
**userInput = getUserResponseToGuess(guess);**
}

Suggestions to improve code about primes?

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

Need to stop two loops from looping within a loop

So my program asks two questions, directions and miles. A user can enter an infinite input for direction and miles, but once the user is done he would simply type "Done" and the loop would break and show the message and the end. I can't get the loops to break need help. Also when a letter is typed for numOfMiles the program just ends. It's suppose to give the error message and reprompt but i can't seem to get that working.
import javax.swing.JOptionPane;
public class taxiService {
public static void main(String [] args) {
//Declare variables
double fareCharge = 5;
double totalMiles = 0;
double finalFareCharged = 0;
double finalxCoord = 0;
double finalyCoord = 0;
double numOfMiles = 0;
double finalCoord = 0;
String error = "Invalid data, please enter valid data!";
String directions = "";
boolean restart = true;
//Prompt for direction and miles
while(restart){
boolean reprompt = true;
boolean reprompt_SecondQuestion = true;
while (reprompt) {
directions = JOptionPane.showInputDialog(null, "Please enter a direction: ");
if (directions.equalsIgnoreCase("East")) {
finalxCoord = finalxCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("West")) {
finalxCoord = finalxCoord - numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("North")) {
finalyCoord = finalyCoord + numOfMiles;
reprompt = false;
}
else if (directions.equalsIgnoreCase("South")) {
finalyCoord = finalyCoord - numOfMiles;
reprompt = false;
}
else {
reprompt = true;
JOptionPane.showMessageDialog(null, error);
}
}
while(reprompt_SecondQuestion)
{
numOfMiles = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter distance in miles: "));
if (numOfMiles > 0) {
totalMiles += numOfMiles;
reprompt_SecondQuestion = false;
}
else {
JOptionPane.showMessageDialog(null, error);
}
}
//Prompt user to type "done"
//Capture user input
if(directions.equalsIgnoreCase("Done"))
{
//Display direction and miles to user
restart = false;
break;
}
else
{
}
}
finalFareCharged = fareCharge + ((numOfMiles / .25) * 2);
JOptionPane.showMessageDialog(null, "miles: " + totalMiles + "\nDirection :" + directions + "\nFinal Charge: " + finalFareCharged + "\nCoordination: " + finalCoord);
}
}
I was able to use this to stop the looping problem
while(done) {
end = JOptionPane.showInputDialog(null, "Is this your destination?(YES/NO)");
if (end.equalsIgnoreCase("Yes")) {
restart = false;
reprompt = false;
reprompt_SecondQuestion = false;
done = false;
break;
}
else if (end.equalsIgnoreCase("No")) {
restart = true;
done = false;
}
else{
JOptionPane.showMessageDialog(null, error);
done = true;
}
}
i still got a problem with numOfMiles. if a letter is entered the program ends. it doesn't give the error message. i've added reprompt_SecondQestion = true; but no change.
I would use labeled break statement (so the intention would be clear for the future reader of the code). Here is the example which prints s0-1-2-3e:
...
System.out.print("s");
labelName:
while (true) {
for (int i = 0; i < 5; i++) {
System.out.print(i);
if (i == 3) {
break labelName; // the "thing" you are looking for
}
}
System.out.print("-");
}
System.out.print("e");
...
This means that you only need to add the label label: and condition statement:
if (directions.equalsIgnoreCase("Done")) {
break label;
}
Your task now, is just to find a proper places to put the code.
Check the condition of your loop. Something like this would suffice:
if(directions.equalsIgnoreCase("Done"))
{
//Display direction and miles to user
reprompt_SecondQuestion = false;
reprompt = false;
restart = false;
break;
}
Also I cannot tell from the brackets where this block is located, if it is at all within the loop. Please check, as proper formatting will save you hours.

How to create a Java Text-Based Hangman Game and other issues

I am creating a Hangman Game in Java and it almost works perfectly. So I have two problems. The first being that:
When the user inputs a letter and the word has repeated letters, how can I make it print both instances of the letter.
I have created a while loop however this loop does not output the Modified word until after the next go. If that makes sense?
The second problem:
I need to be able to prevent the user from entering the same letter twice
I have attempted Lists and arrays and hash sets. All sorts but none seem to work.
My code is below:
There may be other threads with same questions but none seem to help as I cannot implement it into this person's code.
import java.util.Scanner;
import java.util.Arrays;
public class Hangman{
public static void main(String []args){
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"","gravity","banana","gate","processor","momentum","earth","star","light","television","pan","cupboard"};
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length);
int counter = 10;
String radmWord = CollectionOfWords[radmNumber];
char[] genRadmLetter = radmWord.toCharArray();
char[] genRadmLetter2 = radmWord.toCharArray();
for (int x = 0; x<genRadmLetter.length; x++){
genRadmLetter[x]='?';
}
System.out.println(String.valueOf(genRadmLetter));
System.out.println("Hello. Guess a letter.");
char guessedLetter = Input.next().charAt(0);
int RW = radmWord.indexOf(guessedLetter);
if (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
System.out.println(genRadmLetter);
}
if (RW == -1){
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
while (counter != 0) {
System.out.println("Guess a letter.");
guessedLetter = Input.next().charAt(0);
RW = radmWord.indexOf(guessedLetter);
if (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
System.out.println(genRadmLetter);
}
if (RW == -1){
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
} else {
System.out.println(genRadmLetter);
while (RW >= 0 ){
genRadmLetter[RW] = guessedLetter;
RW = radmWord.indexOf(guessedLetter, RW+1);
}
}
boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
if (result == true){
break;
}
if (counter == 0){
break;
}
}
if (counter == 0){
System.out.println("You lose. The word was: " + radmWord);
}
else {
System.out.println("Well done, you have guessed the word.");
System.out.println("Your final score is: " + counter);
}
}
}
Instead of using...
int RW = radmWord.indexOf(guessedLetter);
To determine if the entered value matches a character, which will only return the first index, you should, instead, use a loop of some kind to check every character
boolean found = false;
for (int rw = 0; rw < genRadmLetter2.length; rw++) {
if (genRadmLetter2[rw] == guessedLetter) {
genRadmLetter[rw] = guessedLetter;
found = true;
}
}
Now, because you're relying on the value of RW to determine if a match was found or not, I changed it so that the boolean found flag can used instead, for example...
if (!found) {
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
You also have duplicate sets of code, which can be reduced to a single do-while loop instead, which will make it easier to read and make changes, for example...
do {
//...
} while (counter != 0);
To your second problem, a Set of some kind would be the simplest solution...
Set<Character> guesses = new HashSet<Character>();
//...
char guessedLetter = Input.next().charAt(0);
if (guesses.contains(guessedLetter)) {
System.out.println("You've used this guess, guess again");
} else {
guesses.add(guessedLetter);
For example...
And because it's not always easy to translate code snippets ... this is my test code...
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Hangman {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"", "gravity", "banana", "gate", "processor", "momentum", "earth", "star", "light", "television", "pan", "cupboard"};
int radmNumber = (int) Math.ceil(Math.random() * CollectionOfWords.length);
int counter = 10;
String radmWord = "banana"; //CollectionOfWords[radmNumber];
char[] genRadmLetter = radmWord.toCharArray();
char[] genRadmLetter2 = radmWord.toCharArray();
for (int x = 0; x < genRadmLetter.length; x++) {
genRadmLetter[x] = '?';
}
Set<Character> guesses = new HashSet<Character>();
do {
System.out.println("Guess a letter.");
System.out.println(String.valueOf(genRadmLetter));
System.out.println("Hello. Guess a letter.");
char guessedLetter = Input.next().charAt(0);
if (guesses.contains(guessedLetter)) {
System.out.println("You've used this guess, guess again");
} else {
guesses.add(guessedLetter);
boolean found = false;
for (int rw = 0; rw < genRadmLetter2.length; rw++) {
if (genRadmLetter2[rw] == guessedLetter) {
genRadmLetter[rw] = guessedLetter;
found = true;
}
}
if (!found) {
System.out.println("Wrong letter, try again.");
counter = counter - 1;
System.out.println("Lives left: " + counter);
}
}
boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
if (result == true) {
break;
}
if (counter == 0) {
break;
}
} while (counter != 0);
if (counter == 0) {
System.out.println("You lose. The word was: " + radmWord);
} else {
System.out.println("Well done, you have guessed the word.");
System.out.println("Your final score is: " + counter);
}
}
}
There are multiple issues with the code:
the typical beginners problem of length vs. max element number
unnecessary duplicate code
a logic issue with the output
as for 1.:
you are using this:
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length)
if you use
int radmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length-1)
you can start the arrey without a empty string and it wont randomly crash
on to 2.
you wont need to duplicate the input code if you use this:
System.out.println(String.valueOf(genRadmLetter));
System.out.print("Hello.");
char guessedLetter;
int RW;
while (counter != 0)
{
System.out.println("Guess a letter.");
...
and finally 3.(your main question)
you do the output before changing it. so this fixes your problem:
...
else
{
while (RW >= 0)
{
genRadmLetter[RW] = guessedLetter;
RW = radmWord.indexOf(guessedLetter, RW + 1);
}
System.out.println(genRadmLetter);
}
So simply move the output behind the while.
I made a little helper clas that could help you...
static class GuessString {
private char[] mask;
private String solution;
private boolean lastGuessResult;
GuessString(String word) {
this.solution = word;
this.mask=word.toCharArray();
Arrays.fill(mask, '?'); // Build a mask like: ??????
}
public String guess(char guess) {
char c = Character.toLowerCase(guess); // case insensitive
int i = solution.indexOf(c);
lastGuessResult = i != -1; // -1 means "not found)
if (lastGuessResult)
while (i != -1) { // this will loop till c is replaced everywhere.
mask[i] = c;
i = solution.indexOf(c, i+1);
}
return new String(mask); // return the updated mask.
}
public boolean lastGuessIsRight() {
return lastGuessResult;
}
public String getCurrent() {
return new String(mask);
}
public boolean isSolved() {
return getCurrent().equals(solution);
}
}

Try catch loops

I am not asking anyone to do my work I just need a little help solving this mismatch. This is my program:
import java.util.InputMismatchException;
import java.util.Scanner;
class FibonacciNumbers {
FibonacciNumbers() //default constructor
{
}
Scanner in = new Scanner(System.in);
public int fOf(int n)
{
if (n == 0) //the base case
{
return 0;
}
else if (n==1)
{
return 1;
}
else
{
return fOf(n-1)+fOf(n-2);
}
}
public static void main(String[] args)
{
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String userInput;
int n = 0;
boolean IsRepeat = true ;
boolean isQuit;
boolean checkException = false;
isQuit = false;
while (!isQuit)
{
try {
{
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
n = in.nextInt();
System.out.print("The Fibanocci number for "+n+" is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? Press 'N' for No or anything else to continue: ");
userInput = in.next();
if(userInput.equalsIgnoreCase("N") )
{
isQuit = true;
System.out.println("Good-bye!");
}
else
{
IsRepeat = true;
}
}
}
catch(InputMismatchException ex) {
userInput = in.nextLine();
if ((userInput.charAt(0) == 'q') || (userInput.charAt(0) == 'Q') )
{
isQuit = true;
System.out.println("Good-bye!");
}
else {
checkException = true;
IsRepeat = true;
System.out.println("Invalid entry, Try again!");
}
}
catch (ArrayIndexOutOfBoundsException a)
{
n = in.nextInt();
if (n<0 || n>46)
{
System.out.println("Invalid entry! Please enter an integer that is greater than 0 but less than 46 :");
checkException = false;//sets boolean value to false, continues the loop
}
else
{
IsRepeat = true;
}
}
}
}
}
I did everything I got everything to work but at this part it is not going as I want it to run:
catch (ArrayIndexOutOfBoundsException a)
{
n = in.nextInt();
if (n<0 || n>46)
{
System.out.println("Invalid entry! Please enter an integer that is greater than 0 but less than 46 :");
checkException = false;//sets boolean value to false, continues the loop
}
else
{
IsRepeat = true;
}
}
When I run it if the user inputs higher than 46 or lower than 0 then ask them for a different input but it is just doing the math. It wont do as i wrote the program.
It throws a "java.lang.StackOverflowError" instead of an "ArrayIndexOutOfBoundsException".
The better way would be to catch an invalid input at
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
n = in.nextInt();
you could set the "n = in.nextInt();" into a do - while- loop,
like:
do {
ask for number
} while (check if number is correct);

Categories

Resources