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);
}
}
Related
public class Game {
public static void main(String[] args) {
String secretWord = "frog";
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0) {
here the loop cycles through the characters in a String, and checks if the user input guessedLetter matches a char in the string. right now the loop cycles through each char starting with the first char in the string through the last, the user must guess the letters in the exact order of they are arranged in the string, how can I fix this so that any character input matching a character in the String will be correct rather than the characters having to be in order?
for (int i = 0; i < secretWord.length(); i++) {
char guessedLetter = input.next().charAt(0);
char currentLetter = secretWord.charAt(i);
if (guessedLetter == currentLetter) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
}
else if (guessedLetter != currentLetter) {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
}
else if (correctGuesses == secretWord.length()) {
System.out.println("You Got It! The Word is: " + secretWord);
}
}
}
}
You could try it as follows:
move all the characters of secretWord to a map (key would be the character and the value would be incidences of that character in the string).
read the character from the keyboard and interate (basically, your logic).
Here is the code.
public static void main(String[] args) {
String secretWord = "frog";
Map<Character, Integer> mapOfLetters = new HashMap<>();
for (char c : secretWord.toCharArray()) {
int count = 1;
if (mapOfLetters.containsKey(c)) {
count = mapOfLetters.get(c) + 1;
}
mapOfLetters.put(c, count);
}
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0 && !mapOfLetters.isEmpty()) {
char guessedLetter = input.next().charAt(0);
if (mapOfLetters.containsKey(guessedLetter)) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
int count = mapOfLetters.get(guessedLetter) - 1;
if (count == 0) {
mapOfLetters.remove(guessedLetter);
} else {
mapOfLetters.put(guessedLetter, count);
}
} else {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
} else if(mapOfLetters.isEmpty()){
System.out.println("You Got It! The Word is: " + secretWord);
}
}
guessedLetter = input.next().charAt(0);
If you want to match the whole UserInput there should not be charAt(0).
On the other hand, if you just want to match any character, at first time you can test guessedLetter == currentLetter is true, then just exit program.
By the way, if you like, just google "KMP algorithm" to learn how to match String.
How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)
I have to create a program that accepts a "tweet" from a user and validates it. First it tests to make sure it is less than 140 characters.
If it is valid, it counts the number of hashtags (#), attribution symbols (#), and links ("http://) are in the string, then prints them out. My program works for hashtags and attributions, but not links. How can I fix this code so that it works?
import java.util.Scanner;
class Testing {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a tweet: ");
String input = scan.nextLine();
int length = input.length();
int count = 0;
int hashtags = 0, attributions = 0, links = 0;
char letter;
if (length > 140) {
System.out.println("Excess characters: " + (length - 140));
} else {
while (count < length) {
letter = input.charAt(count);
if (letter =='#') {
hashtags++;
count++;
}
if (letter == '#') {
attributions++;
count++;
}
if (letter == 'h') {
String test = input.substring(count,count+6);
test = test.toLowerCase();
if (test == "http://") {
links++;
count++;
} else {
count++;
}
} else {
count ++;
}
}
System.out.println("Length Correct");
System.out.println("Number of Hashtags: " + hashtags);
System.out.println("Number of Attributions: " + attributions);
System.out.println("Number of Links: " + links);
}
}
I think your code will not work with link like http://test.com/ingex.php?p=1#section. Use regular expressions instead of if () else {} if () else {}. And keep in mind: there is no token(mention, hashtag, link) which contains other token.
import java.util.Scanner;
class Testing
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a tweet: ");
String input = scan.nextLine();
int length = input.length();
int count = 0;
int hashtags = 0, attributions = 0, links = 0;
char letter;
if (length > 140)
{
System.out.println("Excess characters: " + (length - 140));
}
else
{
while (count < length)
{
letter = input.charAt(count);
if (letter =='#')
{
hashtags ++;
count ++;
}
if (letter == '#')
{
attributions ++;
count ++;
}
if (letter == 'h')
{
//String test = input.substring(count,count+6);
//test = test.toLowerCase();
if (input.startsWith("http://", count))
{
links ++;
count++;
}
else
{
count++;
}
}
else
{
count ++;
}
}
System.out.println("Length Correct");
System.out.println("Number of Hashtags: " + hashtags);
System.out.println("Number of Attributions: " + attributions);
System.out.println("Number of Links: " + links);
}
}
}
I changed your code in a few ways, the biggest being that instead of the == you had for checking if the links start with "http://". I also used startsWith(String s, int index) because like #Robin said, anything starting with an h would probably mess up your program.
I also used count to specify where it should start, basically the index part of you parameter
You may find additional functions and documentation in the Strings class javadoc of use.
My professor assigned to write a prime number "finder". Where the number you input will display if it's a prime or even number, then display the next prime number. He wants us to give an error message when the wrong input is keyed in. I figured the negative integer portion is simple, but I cannot figure out the character input. Or if the character is not a digit. How would i block non numeric inputs?
Also, the system is supposed to exit at three CONSECUTIVE erroneous inputs. How would I reset the counter? The way i have written the program, if the user makes two errors but the next ones are acceptable, then make another error. (thus not being consecutive.) the program closes.
This is my first programing course so I'm not to savvy in it. Any help would be greatly appreciated.
Also, i have to use scanner, and the two methods.
/**
*
* #param n
* #return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while ( n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if ( n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
import java.util.Scanner;
public class SOQ5B
{
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer;
int counter = 0;
int n;
boolean playAgain = true;
boolean isNum;
boolean isNum2;
boolean continuePermitted = true;
Scanner input = new Scanner(System.in);
String s;
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
s = input.nextLine();
isNum = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum = false;
}
}
if(isNum)
{
counter = 0;
n = Integer.parseInt(s);
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
}
else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
do
{
continuePermitted = true;
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
s = input.nextLine();
isNum2 = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum2 = false;
}
}
if(isNum2)
{
answer = Integer.parseInt(s);
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
else
{
System.out.println("Incorrect response.");
continuePermitted = false;
//if answering the yes or no question incorrectly is part of the 3 strikes
//then uncomment the following lines of code
/*
counter++;
}
if(counter >= 3)
{
System.out.println("3 strikes you out");
System.exit(0);
*/
}
}while(!continuePermitted);
}
else
{
System.out.print("\nIncorrect input. Number must be a positive integer.\n");
counter++;
}
if(counter>=3)
{
System.out.println("3 strikes and you're out!");
System.exit(0);
}
} while (playAgain != false);
}
}
In the future, I recommend you research your questions on the internet before bringing the question here. There were several other places that could've easily answered your question.
Now as for your actual question, notice how I changed your code at the line that says s = input.nextLine()? What I did there is checked to see if each digit in the string was any number between and including 0-9. Not only was I able to check if they were all numbers, but I was also able to see if they were all positive too as you would have to put a - in order for it to be negative. Along with that, you also have a boolean that only works when the input is a positive number. If not, it checks 3 times to make sure your program doesn't mess up. Furthermore, I even commented out another section that allows the 3 strikes to include if answering the yes no question counts as a strike. If there any other questions, just ask and I will edit my answer.
You are trying to take input using Scanner class with
int n = input.nextInt();
If you enter a character in place of number here you will get java.util.InputMismatchException
What you can do is something like
try {
int n = input.nextInt();
} catch (InputMismatchException e) {
//handle the error scenario where the input is a character
System.out.println("Enter Valid Input");
}
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;
};