How do I exit a nested while loop in java? - java

EDIT: Since my program still doesn't work, I posted the entire method just in case there is another problem.
I want to exit this program if the user inputs 'n' when prompted:
char again = 'y';
while (again == 'y' || again == 'Y')
{
String ans = IBIO.inputString ("Unscramble: OBORSLW (Hint: Shellder latches onto its tail.) ");
int tries = 0;
while (!ans.toLowerCase ().equals ("slowbro"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries++;
ans = IBIO.inputString ("\nUnscramble: OBORSLW (Hint: Shellder latches onto its tail.) ");
if (tries > 3)
{
System.out.println ("The correct answer was SLOWBRO.");
again = IBIO.inputChar ("Play again? (y/n) ");
break;
}
}
System.out.println ("Correct.");
System.out.println ("\nQuestion #2 - ");
String ans2 = IBIO.inputString ("\nUnscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ");
int tries2 = 0;
while (!ans2.toLowerCase ().equals ("graveler"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries2++;
ans2 = IBIO.inputString ("\nUnscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ");
if (tries2 > 3)
{
System.out.println ("The correct answer was GRAVELER.");
again = IBIO.inputChar ("Play again? (y/n) ");
if (again != 'y' || again != 'Y')
break;
}
}
System.out.println ("Correct.");
System.out.println ("\nQuestion #3 -");
String ans3 = IBIO.inputString ("\nUnscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ");
int tries3 = 0;
while (!ans3.toLowerCase ().equals ("gastly"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries3++;
ans3 = IBIO.inputString ("\nUnscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ");
if (tries3 > 3)
{
System.out.println ("The correct answer was GASTLY.");
again = IBIO.inputChar ("Play again? (y/n) ");
if (again != 'y' || again != 'Y')
break;
}
}
printSlow ("Correct.");
printSlow ("\nWell Done, " +name+ "! You have passed the test! I'm so happy for you!!");
break;
}
}
Whenever I purposely input a false value multiple times, I get told the right answer, and can try again if I want to. This part works. However, if I don't want to continue, the program just continues by itself and proceeds to the next question. How can I stop the entire program?

char again = 'y';
while (again == 'y' || again == 'Y')
{
String ans = IBIO.inputString ("Unscramble: OBORSLW (Hint: Shelder latches onto its tail.) ");
int tries = 0;
boolean flag= false;
while (!ans.toLowerCase ().equals ("slowbro"))
{
System.out.println ("Incorrect. Wrong answer. Try again.");
tries++;
ans = IBIO.inputString ("\nUnscramble: OBORSLW (Hint: Shelder latches onto its tail.) ");
if (tries > 3)
{
System.out.println ("The correct answer was SLOWBRO.");
again = IBIO.inputChar ("Play again? (y/n) ");
flag = true;
break;
}
}
if(flag==true){
break;
}
your mean this ?

EDIT: I have modify codes to suit your requirements. Please check it out.
Original: I think first of all you have to write out what is your IBIO class here so that people are able to help you debug.
I have found out IBIO class online and tested your program, but it has performed correctly.
Below is my code.
Main.java:
public class Main {
private static boolean verifyAnswer(String candidate, String answer) {
if (candidate.toLowerCase().equals(answer))
return true;
else {
System.out.println("Incorrect. Wrong answer. Try again.");
return false;
}
}
private static boolean playGame(int questionNumber, String answer, String question) {
String candidate;
System.out.println("Question #" + questionNumber + " - ");
int tries = 0;
do {
tries++;
if (tries > 3) {
System.out.println("The correct answer was " + answer + ".");
char again = IBIO.inputChar("Play again? (y/n) ");
if (again != 'y' && again != 'Y')
System.exit(0);
else
return false;
}
candidate = IBIO.inputString(question);
} while (!verifyAnswer(candidate, answer));
System.out.println("Correct.");
return true;
}
public static void main(String[] args) {
while (!playGame(1, "slowbro", "Unscramble: OBORSLW (Hint: Shellder latches onto its tail.) ")) ;
while (!playGame(2, "graveler", "Unscramble: RVLEGERA (Hint: It rolls down slopes without slowing down.) ")) ;
while (!playGame(3, "gastly", "Unscramble: TYSGLA (Hint: It's almost invisible and is gaseous.) ")) ;
}
}
IBIO.java:
//---- IBIO - Below are simplified input and output methods ----
//===========================================================
// IBIO Standard Input and Output
// These methods must be copied into your program(s).
//===========================================================
public class IBIO {
static void output(String info) {
System.out.println(info);
}
static void output(char info) {
System.out.println(info);
}
static void output(byte info) {
System.out.println(info);
}
static void output(int info) {
System.out.println(info);
}
static void output(long info) {
System.out.println(info);
}
static void output(double info) {
System.out.println(info);
}
static void output(boolean info) {
System.out.println(info);
}
static String input(String prompt) {
String inputLine = "";
System.out.print(prompt);
try {
inputLine = (new java.io.BufferedReader(
new java.io.InputStreamReader(System.in))).readLine();
} catch (Exception e) {
String err = e.toString();
System.out.println(err);
inputLine = "";
}
return inputLine;
}
static String inputString(String prompt) {
return input(prompt);
}
static String input() {
return input("");
}
static int inputInt() {
return inputInt("");
}
static double inputDouble() {
return inputDouble("");
}
static char inputChar(String prompt) {
char result = (char) 0;
try {
result = input(prompt).charAt(0);
} catch (Exception e) {
result = (char) 0;
}
return result;
}
static byte inputByte(String prompt) {
byte result = 0;
try {
result = Byte.valueOf(input(prompt).trim()).byteValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static int inputInt(String prompt) {
int result = 0;
try {
result = Integer.valueOf(
input(prompt).trim()).intValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static long inputLong(String prompt) {
long result = 0;
try {
result = Long.valueOf(input(prompt).trim()).longValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static double inputDouble(String prompt) {
double result = 0;
try {
result = Double.valueOf(
input(prompt).trim()).doubleValue();
} catch (Exception e) {
result = 0;
}
return result;
}
static boolean inputBoolean(String prompt) {
boolean result = false;
try {
result = Boolean.valueOf(
input(prompt).trim()).booleanValue();
} catch (Exception e) {
result = false;
}
return result;
}
//=========== end IBIO ===========================================//
}
My environment: Intellij Community 2016.1.1 + jdk 8 + Windows 7 x64

Related

For two integer user inputs, how to detect that a string has been passed on the very first input?

This is my code. A program to check for prime numbers between user inputs, 'start' and 'stop'.
import java.util.*;
public class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter start: ");
String start = sc.nextLine();
if(start.equalsIgnoreCase("stop"))
{
break;
}
System.out.println("Enter stop: ");
String stop = sc.nextLine();
if(stop.equalsIgnoreCase("stop"))
{
break;
}
try
{
int s1 = Integer.parseInt(start);
try
{
int s2 = Integer.parseInt(stop);
for(int i = s1; i<=s2;i++)
{
if(p1.isPrime(i))
{
System.out.print(i+" ");
}
}
System.out.println("");
}
catch(java.lang.NumberFormatException er)
{
System.out.println("Invalid Input");
}
}
catch(java.lang.NumberFormatException er1)
{
System.out.println("Invalid Input");
}
}
}
}
When taking start input, if I enter any string, I want the code to instantly detect NumberFormatException and ask for the same input again.
What happens instead, is that, it takes both inputs, whether string and integer, and only then evaluates whether it's a string.
I don't use sc.nextLine() because I want the stop functionality. I want the program to stop execution if I input "stop" anywhere.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int start = -1;
int stop = -1;
while (true)
{
if (start == -1)
{
System.out.println("Enter start: ");
if (sc.hasNextInt())
{
start = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
if (stop == -1)
{
System.out.println("Enter stop: ");
if (sc.hasNextInt())
{
stop = sc.nextInt();
} else if (sc.nextLine().equalsIgnoreCase("stop")) break;
else
{
System.out.println("Invalid Input");
continue;
}
}
for (int i = start; i <= stop; i++)
{
// Prime number method call here
System.out.print(i + " ");
}
System.out.println();
start = stop = -1;
}
}

How to make the code run reversly? from Roman number to decimal number

I already wrote a code that convert from decimal number to roman number, however, i want it to do opposite way so how can i make it possible? (This is my previous code: http://pastebin.com/QFKi0xJh ) thank you! and here is my code right now.
I am just a beginner so my code is look little bit basic, please apology for that.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.length()==1 && i.charAt(0)=='q' || i.charAt(0)=='Q') {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int n=0;
if (numeral.equalsIgnoreCase("m")) {
n-=1000;
}
else if (numeral.equalsIgnoreCase("d")) {
n=500;
}
else if (numeral.equalsIgnoreCase("c")) {
n=100;
}
else if (numeral.equalsIgnoreCase("l")) {
n=50;
}
else if (numeral.equalsIgnoreCase("x")) {
n=10;
}
else if (numeral.equalsIgnoreCase("v")) {
n=5;
}
else if (numeral.equalsIgnoreCase("i")) {
n=1;
}
return n;
}

Hangman, exits the game without getting the user response (loop)

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Scanner NoSuchElementException

I'm having a problem with my Java assignment. I'm getting an unexpected exception, specifically:
java.util.NoSuchElementException: No line found
I am using Scanner(System.in) and the program is continually reading nothing and repeating the "invalid format" exception text. If I enter a correctly valued int, the first part passes and then the double part immediately goes into this exception. If I enter an incorrectly valued int, then it starts looping the exception.
Here is my code:
import java.util.Scanner;
public class Program_4 {
public static void main(String[] args) {
getValidInt("Enter an integer from 5 to 50",5,50);
getValidDouble("Enter a double from 5.0 to 50.0",5.0,50.0);
getValidString("Enter a string with length from 5 to 8 characters",5,8);
}
public static int getInt(String prompt)
{
Scanner sc = new Scanner(System.in);
int i = 0;
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = Integer.parseInt(sc.nextLine());
isValid = true;
}
catch (Exception e)
{
System.out.println(e);
System.out.print("Invalid Format: ");
isValid = false;
}
}
while (isValid == false);
sc.close();
return i;
}
public static int getValidInt(String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
do
{
i = getInt(prompt);
if(i < min) System.out.println("Value must be >= " + min);
else if(i > max) System.out.println("Value must be <= " + max);
else isValid = true;
} while (isValid == false);
return i;
}
public static double getDouble(String prompt)
{
Scanner sc = new Scanner(System.in);
double i = 0.0;
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = Double.parseDouble(sc.nextLine());
isValid = true;
}
catch (Exception e)
{
System.out.println(e);
System.out.println("Invalid Format: ");
isValid = false;
}
} while (isValid == false);
sc.close();
return i;
}
public static double getValidDouble(String prompt, double min, double max)
{
int i = 0;
boolean isValid = false;
do
{
i = getInt(prompt);
if(i < min) System.out.println("Value must be >= " + min);
else if(i > max) System.out.println("Value must be <= " + max);
else isValid = true;
} while (isValid == false);
return i;
}
public static String getString(String prompt)
{
Scanner sc = new Scanner(System.in);
String i="";
boolean isValid;
do
{
try
{
System.out.print(prompt + ": ");
i = sc.nextLine();
isValid = true;
}
catch (Exception e)
{
System.out.print("Invalid Format: ");
isValid = false;
}
} while (isValid == false);
sc.close();
return i;
}
public static String getValidString(String prompt, int min, int max)
{
String i;
boolean isValid = false;
do
{
i = getString(prompt);
if(i.length() < min) System.out.println("String must be more than " + min + " characters.");
else if(i.length() > max) System.out.println("String must be more than " + max + " characters.");
else isValid = true;
} while (isValid == false);
return i;
}
}
You have more than one Scanner that you close, which closes the underlying InputStream, therefore another Scanner can no longer read from the same InputStream and a NoSuchElementException results.
For console apps, use a single Scanner to read from System.in.
Since you print out the same message in all three places where an exception is caught, it is difficult to say with any certainty what is going on:
Use printStackTrace() to find out where the exception is happening
Don't catch Exception like that. Catch the exceptions that you are expecting and that your code is designed to handle. If you catch Exception you could end up catching all sorts of unexpected exceptions (NPE, end of file, etc) ... and incorrectly reporting them as "Invalid format".

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