Try catch loops - java

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);

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;
}
}

Why is this loop looping the code but not performing the correct actions?

When I click retry on this code, it work's and asks how many times to loop flip a coin but the just prints "Flipping Coin(s)" and does nothing. Anyone know how to fix it? I think the error might be coming from X already being less than numloop but I am not sure how to fix it.
Here is my code:
import java.util.Scanner;
public class coinFlip {
public static void main (String[]args)throws InterruptedException {
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
int x = 0;
String choice;
Boolean bool = true;
while (bool=true){
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}
}
Thank You So Much!
If you move int x=0 from outside of your initial while loop to inside of it you won't have this issue. It will reset every time the user retries.
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
String choice;
Boolean bool = true;
while (bool=true){
int x = 0;
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}

How do I exit a nested while loop in 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

First do-while loop not functioning properly

There seems to be something with my code. My code detects non-integers and keep asking the user to input a positive #, but when you insert a negative #, it just ask the user to input a positive just once. What is wrong? Something with my do-while loop for sure.
I'm just focusing on the firstN, then I could do the secondN.
import java.util.Scanner;
public class scratch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstN = 0;
int secondN = 0;
boolean isNumber = false;
boolean isNumPos = false;
System.out.print("Enter a positive integer: ");
do {
if (input.hasNextInt()) {
firstN = input.nextInt();
isNumber = true;
}
if (firstN > 0) {
isNumPos = true;
isNumber = true;
break;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
continue;
}
} while (!(isNumber) || !(isNumPos));
System.out.print("Enter another positive integer: ");
do {
if (input.hasNextInt()) {
secondN = input.nextInt();
isNumber = true;
}
if (secondN > 0) {
isNumPos = true;
isNumber = true;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
}
} while (!(isNumber) || !(isNumPos));
System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));
}
public static int gCd(int firstN, int secondN) {
if (secondN == 0) {
return firstN;
} else
return gCd(secondN, firstN % secondN);
}
}
You read the input twice in such case:
firstN = input.nextInt();
...
input.next ();
Add some indication variable or reorganize the code so when you read via first read, avoid the second one.
Try this piece of code
while (true){
System.out.println("Please enter Positive number");
boolean hasNextInt = scanner.hasNextInt();
if(hasNextInt){
int firstNum = scanner.nextInt();
if(firstNum>0){
break;
}else{
continue;
}
}else{
scanner.next();
continue;
}
}

How to reject inputs that are non digit characters?

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");
}

Categories

Resources