using string to break out of loop in java - java

I simply would like to break out of a while true loop if the user enters in "STOP" into the scanner. Currently my scanner only takes in integers and I believe this is where the problem lies. If I try to type in "STOP" I get many errors saying "exception in thread main". Here is a snippet of my code:
public class algorithm {
private Scanner input = new Scanner(System.in);
int n;
while (true){
System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
System.out.println("Type 'STOP' to end the program");
n = input.nextInt();
String strN = String.valueOf(n); //convert integer to string
if (new String(strN).equals("STOP")){ //if string is STOP, breaks
System.out.println("Thanks for using my program");
break;
}
if (n % 2 == 0){
System.out.println(n+" is even");
continue;
}
else{
System.out.println(n+" is odd");
continue;
I know I am missing some closing curly braces but rest assured they are all there in my actual code. Thanks.
Here is the error I am getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at OddOrEven.algorithm.checker(algorithm.java:13)
at OddOrEven.main.main(main.java:7)

You've already identified the problem yourself - your Scanner reads only integers:
int n;
...
n = input.nextInt();
so it's impossible for the variable n (an int) to contain the string "STOP" (and your Scanner throws an exception anyway when you call nextInt() but it encounters a string, such as "STOP", that it cannot convert to an int).
To do this, you need to read strings from the input (probably using Scanner.nextLine()), check whether they are "STOP", and if not, only then attempt to convert them to ints using something like:
int n = Integer.parseInt(mystring)
To handle garbage input (neither STOP nor an integer), wrap the parseInt line in a try-catch block so that you can detect when the input is garbage by catching the Exception
try {
int i = Integer.parseInt(mystring);
// do something with the int
}
catch (NumberFormatException e) {
// display warning message to the user instead
}
See also this related question.

The most simple way is probably to use input.next() instead of input.nextInt(). Using input.next() will read input in as a String, then you can check if the input is equal to "QUIT", if it is not you can use Integer.parseInt to parse the Integer from the read string

Something like below, should work out.
NOTE: havent tested compile errors, just wrote it out(but you get a gist)
public Scanner input = new Scanner(System.in);
int n;
while (true){
System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
System.out.println("Type 'STOP' to end the program");
n = input.next();
Integer input;
// String strN = String.valueOf(n); //convert integer to string
if (strN.equals("STOP")){ //if string is STOP, breaks
System.out.println("Thanks for using my program");
break;
}
else{
try{
input= Integer.parseInt(strN);
}
catch(Exception e)
{
System.out.println("Please enter a number");
}
}
if (input % 2 == 0){
System.out.println(n+" is even");
continue;
}
else{
System.out.println(n+" is odd");
continue;
}

Related

How can I remove this java exception error in my code?

When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn't input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?
MY CODE
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
When I input a string this message gets displayed. However, I just wanted to tell the user they exerted the wrong value and I wanted the program to quit.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at MainHandler.main(MainHandler.java:22)
I did try use hasNextInt at one point to try get rid of the exception error but I get an error when I use hasNextInt. https://imgur.com/a/OK8r3RH
Try with something like this. You surround your input inside a try-catch and as long as you get an Exception, you ask the user to put a number again. As soon as the input is valid (a number) you can proceed with your code:
boolean canProceed = false;
int number = -1;
while (!canProceed) {
try {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
number = Integer.parseInt(input.nextLine());
canProceed = true;
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
if (number > 0 && number <= 100) {
System.out.println("That's fine");
}
else {
System.exit(0);
}
You would need double if you are entering decimal numbers and put your code inside try/catch block
try{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
double decimal = input.nextDouble();
if (decimal > 0 && decimal <= 100) {
}
else {
System.exit(0);
}
}catch (Exception e){
System.out.println(e);
}
Try binding your code inside try and catch blocks like this:
try{
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
}
catch(Exception e){
System.out.println("You enter wrong value");
}
The code you posted works just fine if the input is provided from the start. However given your "Enter a number:" message I suppose you want the user to provide the input interactively, in which case you'll have to implement a waiting loop :
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
while (!scanner.hasNextInt()) {
if (scanner.hasNextLine()) {
scanner.nextLine(); // we've got something but it's not a number, discard it
}
}
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
//code
}
else {
System.exit(0);
}
In this case the loop will continue until it finds an integer to read from the input, discarding lines of input if they don't start with an integer.
I just thought I would throw this in here since it is another flexible alternative to accomplishing the task. It utilizes the Scanner#nextLine() method with input validation to ensure that what is supplied is actually what is expected without the worry of an exception being thrown.
Validation is done using the String#matches() method supplied with a small Regular Expression (RegEx) to insist that numerical digits are supplied and that the supplied value is within the desired inclusive unsigned numerical range of 1 to 100. If the validation fails then the User is expected to try again or enter 'Q' (or anything that starts with Q - case insensitive) to quit.
Scanner input = new Scanner(System.in);
int intValue = 0;
String numberString = "";
// Prompt and Input...
while (intValue == 0) {
System.out.print("Enter a number (or 'q' to quit): --> ");
numberString = input.nextLine().toLowerCase();
//Quit..
if (numberString.charAt(0) == 'q') {
System.exit(0);
}
// Integer (unsigned - Range 1 to 100)...
else if (numberString.matches("100|[1-9][0-9]{1}?")) {
intValue = Integer.parseInt(numberString);
}
else {
System.err.println("Invalid numerical value supplied or the supplied");
System.err.println("value is not in the inclusive range of 1 to 100!");
System.err.println("Try Again...");
System.err.println();
}
}
//Your processing code here.
System.out.println("The value you entered is: --> " + intValue);
Explanation for the RegEx used within the String#matches() method:
100|[1-9][0-9]{1}?
1st Alternative 100
100 matches the characters 100 literally (case sensitive)
2nd Alternative [1-9][0-9]{1}?
Match a single character present in the list below [1-9]
1-9 a single character in the range between 1 (index 49) and 9 (index 57) (case sensitive)
Match a single character present in the list below [0-9]{1}?
{1}? Quantifier — Matches exactly one time (meaningless quantifier)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
If you want to change your numerical range then you may find this site useful.

Enter a string to integer scanner [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I want to say enter an integer when someone trying to enter a string in this code.
Can you help me?
Here is my code:
import java.util.Scanner;
public class kl {
public static void main(String[] args) {
boolean primen = true;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a positive integer that is prime or not : ");
int ncheck = input.nextInt();
if (ncheck < 2) {
primen = false;
}
for (int i = 2; i < ncheck; i++) {
if (ncheck % i == 0) {
primen = false;
break;
}
}
if (primen == true) {
System.out.println(ncheck + " is a prime number.");
}
else {
System.out.println(ncheck + " is not a prime number.");
}
}
}
You can find your solution here: Exception handling, Or use codes below
Here is your complete code:
while(true){
System.out.print("Please enter a positive integer that is prime or not : ");
try{
int i = input.nextInt();
break;
}catch(InputMismatchException e){
System.out.print("Wrong type input, pls try again!");
input.nextLine(); \\ prevent infinite loop
}
You can see: I use a Exception handle processor to catch the InputMismatchException and print on console the message. You can replace InputMismatchException by Exception. It's largest Exception Handler class in java
There are two approaches you can use with Scanner.
Call nextInt() and then catch and handle the InputMismatchException that you will get if the next input token isn't an integer.
Call hasNextInt(). If that returns true then call nextInt().
In either case, if you expected an integer and the user entered something else, then neither nextInt() or hasNextInt() will "consume" the unexpected characters. So if you want the user to try try again, you need to call nextLine() which will read all remaining characters on the line. You will typically discard them.
For more information on handling exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
For more information on using Scanner:
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

How to continue loop inside of Try Catch for Guessing game

So my problem is that i don't know how to continue my program when i do the try and catch for input errors. I tried using the "continue;" code after my catch statement but that just loops my program uncontrollably. I need the program to start where it left off after the user does an incorrect input. Any help would be appreciated. Note that this was an assignment BUT I'm going above and beyond by handling junk in my code.
//Import library
import java.io.*;
import java.util.*;
//File name
public class GuessingGame
{
//Main throws Input and output error
public static void main (String [] args) throws IOException
{
//inputs for users
Scanner in = new Scanner (System.in);
Scanner i = new Scanner (System.in);
//variables for the loop, random number, character and counter
int guess = 0;
int rnd;
char decision;
boolean loop = false;
//random number generator
Random random = new Random();
rnd = random.nextInt(100) + 1;
//loops the guess and input
while (!loop){
try{
System.out.println(rnd);
//prompt the user
System.out.println(" Please guess a number between 1-100. Press 0 to exit.");
int num = in.nextInt();
//if statements
if (num==0)
{
//when user types '0' it ends the program
System.exit(0);
System.out.println("You gave up!.... Reseting program...");
}
else if (num>rnd)
{
//prints too big, adds to counter 'guess'
System.out.println("The number is too big!");
guess++;
}
else if (num<rnd)
{
//prints too small, adds to counter 'guess'
System.out.println("The number is too small!");
guess++;
}
else
{
//prints correct, adds to counter, dsiplays # of guesses and ends loop
System.out.println("You guessed the number right!!");
guess++;
System.out.print(" # of guesses: " + guess);
//Note**: i could've just put 'break;' but the compiler would'nt read the rest of the code below
loop = true;
//loops the case untill correct input is chosen either 'Y' or 'N'
while(true){
//prompt the user if they want to play again
System.out.println(" Would you like to play again? Y/N?");
decision = i.nextLine().charAt(0);
switch (decision) {
case 'Y':
case 'y':
//calls main, basically restarts the game
GuessingGame.main(args);
break;
case 'N':
case 'n':
System.out.println("Bye!");
//exits the program completely
System.exit(0);
break;
default:
//if incorrect input, this prints
System.out.println("Please enter a Yes or No <Y/N>");
}
}
}
}
//catches input errors
catch (Exception e){
System.out.println("Only numbers!!!");
//GuessingGame.main(args);
continue;
}
}
}
Try this move your catch up because you are only testing the input. Also add in.nextLine() in your catch to eat up the character that is left behind.
while (!loop){
int num;
try{
System.out.println(rnd);
//prompt the user
System.out.println(" Please guess a number between 1-100. Press 0 to exit.");
num = in.nextInt();
}
catch (Exception e){
System.out.println("Only numbers!!!");
//GuessingGame.main(args);
in.nextLine();
continue;
}
Scanner by default splits the standard input by spaces and keeps an index of how many substrings have been parsed. The specific method you call (.nextWhatever) will attempt to parse the next string in line to its expected type and will only increase the index if it's successful; if there's no stream left to parse, it will await new input.
The reason your loop is infinite is because it failed to parse the token to an integer and isn't increasing the index. There are two ways to skip the invalid input. nextLine() will skip the rest of the stream waiting. For example, if the input was "1 abc 2"
in.nextInt(); // equals 1
// in.nextInt() would fail
in.nextLine(); // equals "abc 2" and if put in your catch would clear the stream
However, if you want to keep trying subsequent tokens (in this case skip "abc" but try "2", which is valid), next() is more appropriate because it will just skip over one token.
try(){
// validate input
int num = in.nextInt();
}
catch(Exception e){
System.out.println("Ignoring your faulty input");
in.next();
}

How do I check to see if the input is an integer?

Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful

Testing for blank input using Scanner class during input validation

I need to ask the user to enter a positive non-zero integer from the console that I will use as a product number in my program.
If I enter any non-integer value, the program correctly enters the while loop.
If I enter a 0 or a negative integer, the program correctly throws the exception (which I catch and handle elsewhere).
When I just press the enter key (or end of line character) it seems that the program just puts the console to another line. I want it to enter the while loop to display the error message. I think the cause is that hasNextInt() will wait until the token is a non end of line character input.
private static void validateProductNumber() throws InvalidProductNumberException {
Scanner keyboard = new Scanner(System.in);
int number;
while(!keyboard.hasNextInt()) {
System.out.println("Number must be an integer. Try again. ");
System.out.println("Enter a new number: ");
keyboard.next();
}
number = keyboard.nextInt();
if (number <= 0)
throw new InvalidProductNumberException();
newNumber = number;
}
Is there another way I can implement my input validation with Scanner class so that it works correctly for all situations?
You can change your loop as follows:
while(true) {
try {
System.out.println("Enter a new number: ");
//read the line and parse it
number = Integer.parseInt(keyboard.nextLine());
break; //break the loop if the input is a valid integer
} catch(Exception ex) {
//print the error message if the input is incorrect
System.out.println("Number must be an integer. Try again. ");
}
}
if (number <= 0)
//...

Categories

Resources