I tried making a menu system to make a user select between four options. To distinguish between the selections I check the int entered. It works but somehow I feel it is not very elegant. Especially when I set the initial value of selectedMenu to 1902475424 to check for when the user entered a mismatcing value. I assumed the user wont accidentally type 1902475424.
Is there a way more simple way to make a menu system or will this do? Is this major flawed?
Yes im a beginner to Java :-)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println(
"1. Start new game\n" +
"2. Load game\n" +
"3. Settings\n" +
"4. Exit\n"
);
}
public void selectMenu() throws InputMismatchException {
int selectedMenu = 1902475424;
Scanner aScanner = new Scanner(System.in);
do {
selectedMenu = 1902475424;
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out
.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
}
if ((selectedMenu < 1 || selectedMenu > 4)
&& (selectedMenu != 1902475424)) {
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
}
} while (selectedMenu == 1902475424
|| (selectedMenu < 1 || selectedMenu > 4));
if (selectedMenu >= 1 && selectedMenu <= 4) {
System.out.println("A new game will now start.");
}
}
}
Your method is leaning into the overkill category :]You can do away with your random value of 1902475424 like so:
public void selectMenu() throws InputMismatchException {
int selectedMenu;
Scanner aScanner = new Scanner(System.in);
do {
try {
System.out.println("Try block begin.");
selectedMenu = aScanner.nextInt();
if(selectedMenu < 1 || selectedMenu > 4) {
System.out.println("Input out of range \"" + selectedMenu + "\". Input..");
}
} catch(InputMismatchException e) {
System.out.println("Catch blok begin.");
System.out.println("Invalid input, please input a number between 1-4.");
aScanner.nextLine();
selectedMenu = 0;
}
} while(selectedMenu < 1 || selectedMenu > 4);
System.out.println("A new game will now start.");
}
Consider the following alternative (pseudocode):
int getMenuOption() {
print(message)
read(input)
if input is valid then return input
else then return getMenuOption()
}
This is recursive, so if the user sits there and enters bad numbers long enough, you could overflow the stack. You could easily augment this to give the user a fixed number of tries:
int getMenuOption(int triesRemaining) {
if (triesRemaining == 0) throw new RetriesExceededException();
print(message)
read(input)
if input is valid then return input
else then return getMenuOption(triesRemaining - 1)
}
Try something like that (I haven't tested it)
import java.util.Scanner;
import java.util.InputMismatchException;
public class Menu {
public void printMenu() {
System.out.println("1. Start new game\n" + "2. Load game\n"
+ "3. Settings\n" + "4. Exit\n");
}
public void selectMenu() throws InputMismatchException {
int selectedMenu;
boolean validSelection = false;
Scanner aScanner = new Scanner(System.in);
while(!validSelection) {
selectedMenu = aScanner.nextInt();
validSelection = true;
switch (selectedMenu) {
case 1:
// doWhen1();
break;
case 2:
// doWhen2();
break;
case 3:
// doWhen3();
break;
case 4:
// doWhen4();
break;
default:
System.out.println("Input out of range \"" + selectedMenu
+ "\". Input a number between 1-4.");
validSelection = false;
}
}
}
}
Here is a revision to the selectMenu() method you provided that should get the job done! I tested it out and it seems to work as expected. :)
public void selectMenu() {
int selectedMenuItem = 0;
Scanner aScanner = new Scanner(System.in);
while(selectedMenuItem == 0){
String userInputMenuItemString = aScanner.nextLine();
try {
int userInputMenuItem = Integer.parseInt(userInputMenuItemString);
if(userInputMenuItem > 0 && userInputMenuItem <= 4){
selectedMenuItem = userInputMenuItem;
}else{
System.out.println("No option #" + Integer.toString(userInputMenuItem) + " exists!\nTry again:");
}
} catch(NumberFormatException ex) {
System.out.println("Please input a number!");
}
}
switch(selectedMenuItem){
case 1:
System.out.println("You chose to start a new game!");
break;
case 2:
System.out.println("You chose to load a game!");
break;
case 3:
System.out.println("You chose to access settings!");
break;
case 4:
System.out.println("You chose to exit. Bye!");
System.exit(0);
break;
}
}
Related
import java.util.Random;
import java.util.Scanner;
public class Activity3 {
public static void main(String[] args) {
//Variables
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10);
do {
System.out.println("Guess the random generated number of the machine from 1-10");
int guess = input.nextInt();
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
} else if (guess <= 0 && guess >= 11) {
System.out.println("Invalid Number!");
}
if (guess > 1 && guess < 10){
System.out.println("You Lose:<");
}
System.out.println("Do you want to try again?");
} while (input.next().equalsIgnoreCase("YES"));
input.close();
}
}
If I guess the correct number it outputs " you win!".
If I guess wrong it outputs "you lose". But If I guess a number that isn't in 1-10 it doesn't output the "Invalid Number" and just proceeds to output the "Do you want to try again?".
Random#nextInt(int) will return a value from 0 to bound - 1, so it's possible that the guess could be 0 in your code. You'd correct this by adding 1 to the guess, for example int num = Machine.nextInt(10) + 1;
Look at your logic...
else if(guess <= 0 && guess >= 11) {
if guess <= 0 AND guess >= 11 ... well, that's impossible.
I would change your logic flow, focusing on "happy paths" first.
That is, is the input within the acceptable range? If so, is guess == num if so, you win, otherwise print error messages.
For example...
Scanner input = new Scanner(System.in);
Random Machine = new Random();
int num = Machine.nextInt(10) + 1;
boolean done = false;
do {
System.out.println("Guess the random generated number of the machine from 1-10");
// Read the WHOLE line of text, removing the new line from the
// buffer which would otherwise be left by Scanner#nextInt
// and would cause no end of issues
String text = input.nextLine();
try {
// Try and parse the text to an int
int guess = Integer.parseInt(text);
if (guess >= 1 && guess <= 10) {
if (guess == num) {
System.out.println("Correct number= " + num);
System.out.println("You Win!");
num = Machine.nextInt(10) + 1;
System.out.println("Would you like to play another game? (Yes/No)");
} else {
System.out.println("Incorrect, guess again");
System.out.println("Do you want to try again? (Yes/No)");
}
// Prompt the user to try again or play another game
text = input.nextLine();
done = !"yes".equals(text.toLowerCase());
} else {
System.out.println("Out of range");
}
} catch (NumberFormatException exp) {
System.out.println("Not a valid number");
}
} while (!done);
public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
so, this is my code for a number guessing game. everything works fine so far execpt if i enter a letter as an input my code crashes. I guess i have to use a try/catch ? If yes where and how do i write it. I am a beginner so have mercy.
I this case, I would put the try catch wrapping where you read the user's input, like so:
public class NewClass12 {
public static void main(String[] args) {
Random generator = new Random();
int numberToGuess = generator.nextInt(10 - 1) + 1;
int yourGuess;
Scanner input = new Scanner(System.in);
int guess = 0;
boolean win = false;
while (!win) {
System.out.println("Guess a number between 1 and 10: ");
try{
yourGuess = input.nextInt();
guess++;
if (yourGuess < 1 || guess > 10) {
System.out.println("Guess is out of range! Enter a number between 1 and 10");
continue;
}
if (yourGuess == numberToGuess) {
win = true;
break;
}
if (yourGuess < numberToGuess) {
System.out.println("Your guess is too low");
} else {
System.out.println("Your guess is too high");
}
} catch (InputMismatchException err){
System.out.println("The input must be a number!");
input.next();
}
}
if (win) {
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + guess + " tries.");
}
}
}
Note that we need the input.next() within the catch, in order to consume the invalid input, so it won't be in a loop.
I would like to handle this situation about inputting wrong string, but error keeps happening because of the else if argument.
Tried try, catch but don't know how to apply it to this code.
import java.util.Scanner;
public class game
{
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
I expect the result from the else block, but when I input wrong string like "c" or "f" and etc, number format exception error: For input string: "c" (or "f" and etc) happens. Thanks for reading this, and hope you solve this problem.
int check = 0;
try{
check = Integer.parseInt(input);
}catch(NumberFormatException e){
System.out.println("Wrong input");
continue;
}
If you loop this input processing,if it enters catch,you may take input again or you can do what you want when invalid input is entered.If there is no exception,check is your input value,then you can use it in your if and else-if statements like
if(check>0){
...
}
Before Else blocks, you can parse the input like this:
if (input.equals("q")) {
System.out.print("quit the game.");
return;
}
int parsedInput = 0;
try {
parsedInput = Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.out.print("Error. Please try again.");
return;
}
Then you can write if-else for integer input like below:
if (parsedInput == 0) { ... }
else if (parsedInput >= 2 && parsedInput <= 9) {...}
Last else is not needed because I moved it to catch block.
try this it can handle exception
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
int check_input = Integer.parseInt(input);
if (check_input == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
} else if (check_input >= 2 && check_input <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
} catch (Exception e) {
System.out.print("Error. Please try again.");
}
}
}
You just need to check the user provided input is number or not. Before parsing it.
I have added new isNumberic method which is returning boolean flag depending user's input and verify it.
public class Game {
public static void main(String[] args) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println(
"if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
Game game = new Game();
boolean isvalid = game.isNumeric(input);
if (input.equals("q")) {
System.out.print("quit the game.");
}
else if (isvalid && Integer.parseInt(input) == 0) {
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (isvalid && Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9) {
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier) {
System.out.print("You're right!");
} else {
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else {
System.out.print("Error. Please try again.");
}
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
}
You can't send values like a , b, c etc for
Integer.parseInt(String s)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
I have try catch block to catch numberformat exception with message to enter valid integer
public static void main(String args[]) {
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
int answer;
int multiplier = (int)(Math.random()*8+2);
int random = (int)(Math.random()*8+2);
try {
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random+"times table has been made automatically.");
System.out.print(random+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == random*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+random*multiplier+".");
}
}
else if (Integer.parseInt(input)>=2 && Integer.parseInt(input)<=9)
{
int number = Integer.parseInt(input);
System.out.println("You chose"+number+" times table.");
System.out.print(number+" X "+multiplier+" = "+"? input your answer ==> ");
answer = s.nextInt();
if (answer == number*multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is "+number*multiplier+".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
catch (NumberFormatException e ) {
System.out.print("pleae enter Valid integer");
}
It's obvious that you are getting this error because you are calling Integer.parseInt on a string variable which doesn't contain an Integer. What you should be doing is putting a check once you get the input to check if the string contains what you need. Something like below
while (true)
{
// Check that the input is between 0 and 9 or q.
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
// If it is not, ask for input again.
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
// If input is correct, break this look.
break;
}
}
Below is the whole code
public class game
{
public static void main(String[] args)
{
System.out.println("let's start the multiplication game.");
System.out.println("which times table do you want to choose?");
System.out.println("if you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
System.out.println("press \"q\" if you want to quit");
System.out.println("==>");
String input;
Scanner s = new Scanner(System.in);
input = s.nextLine();
while (true)
{
if (!((input.charAt(0) >= '0' && input.charAt(0) <= '9') || input.charAt(0) == 'q'))
{
System.out.println("Input is not correct. If you want to do it by your choice, please input number among 2~9. Or if you want to do it randomly, please input number 0");
input = s.nextLine();
}
else {
break;
}
}
int answer;
int multiplier = (int) (Math.random() * 8 + 2);
int random = (int) (Math.random() * 8 + 2);
if (input.equals("q"))
{
System.out.print("quit the game.");
}
else if (Integer.parseInt(input) == 0)
{
System.out.println(random + "times table has been made automatically.");
System.out.print(random + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == random * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + random * multiplier + ".");
}
}
else if (Integer.parseInt(input) >= 2 && Integer.parseInt(input) <= 9)
{
int number = Integer.parseInt(input);
System.out.println("You chose" + number + " times table.");
System.out.print(number + " X " + multiplier + " = " + "? input your answer ==> ");
answer = s.nextInt();
if (answer == number * multiplier)
{
System.out.print("You're right!");
}
else
{
System.out.print("Wrong! The right answer is " + number * multiplier + ".");
}
}
else
{
System.out.print("Error. Please try again.");
}
}
}
Verify input in two separate if/else blocks. Add this code to your "else" statement to catch strings other than "q".
else{
try {
int inputNumber = Integer.parseInt(input);
if(inputNumber == 0) {
// code..
} else if (inputNumber >= 2 && inputNumber <= 9) {
// code..
}
} catch(java.lang.NumberFormatException e) {
System.out.print("Error. Please try again.");
}
}
why don't use try catch?
if (input.equals("q")) {
System.out.print("quit the game.");
}
try {
Integer i = Integer.parseInt(input);
}catch (NumberFormatException e){
System.out.print("Error. Please try again.");
return;
}
Wrote a roshambo program, ran it once, worked fine, ran it again and the following errors popped up:
RoShamBo!
Play Game
Show Score
Quit
1
Which do you choose?
Rock
Paper
Scissors
2
Which do you choose?
Rock
Paper
Scissors
Invalid Entry, Please Try Again.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at RoShamBo.getUserChoice(RoShamBo.java:82)
at RoShamBo.winner(RoShamBo.java:112)
at RoShamBo.main(RoShamBo.java:27)
not sure on how to deal with these type of errors, this my first time using methods so i'm thinking it has to do with how I called each method? please help.
thanks in advance.
import java.util.Scanner;
public class RoShamBo
{
public static void main(String[] args)
{
System.out.println("RoShamBo!");
System.out.println("1. Play Game");
System.out.println("2. Show Score");
System.out.println("3. Quit");
Scanner userInput = new Scanner(System.in);
if(userInput.hasNextInt())
{
int userIn = userInput.nextInt();
if(userIn == 1)
{
getUserChoice();
getCompChoice();
winner();
}
else if(userIn == 2)
{
scores();
}
else if(userIn == 3)
{
System.out.println("Qutiing: Final Score was: ");
scores();
userInput.close();
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
userInput.next();
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
userInput.next();
}
}
public static String getUserChoice()
{
// ask player for a move : playerMove
System.out.println("Which do you choose?");
System.out.println("1. Rock");
System.out.println("2. Paper");
System.out.println("3. Scissors");
Scanner input = new Scanner(System.in);
String userChoice = " ";
if (input.hasNextInt())
{
int userInput = input.nextInt();
switch(userInput)
{
case 1:
userChoice = "Rock";
break;
case 2:
userChoice = "Paper";
break;
case 3:
userChoice = "Scissors";
break;
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.");
input.next();
}
input.close();
return userChoice;
}
private static String getCompChoice()
{
//Method for getting Computers move
int compChoice = (int) ( 1 + (Math.random() * 3));
String compMove = " ";
switch(compChoice)
{
case 1:
compMove = "Rock";
break;
case 2:
compMove = "Paper";
break;
case 3:
compMove = "Scissors";
break;
}
return compMove;
}
public static String winner()
{
String winnerIs = " ";
String comp = getCompChoice();
String user = getUserChoice();
if(user.equals("Rock") && comp.equals("Scissors") ||
user.equals("Paper") && comp.equals("Rock") ||
user.equals("Scissors") && comp.equals("Paper"))
{
System.out.println("You Win!");
}
else
{
System.out.println("You Lose");
}
return winnerIs;
}
public static void scores()
{
int compCount = 0;
int userCount = 0;
if (winner().equals("You Win!"))
{
userCount++;
}
else
{
compCount++;
}
System.out.println("Player = " + userCount );
System.out.println("Computer = " + compCount );
}
}
Probably here
{
System.out.println("Invalid Entry, Please Try Again.");
input.next();
}
you are doing a next() without checking for has*().
Your stack gives one hint.
at java.util.Scanner.next(Unknown Source).
and
Exception in thread "main" java.util.NoSuchElementException
Turning to the documentation here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29
part that is of interest to you:
Throws:
NoSuchElementException - if no more tokens are available
You call .next()
but what do you want to read? Is there anything waiting in input buffer? Also, see my comment, meaning that your logic is busted.Rethink your game logic instead of fixing it.
Giving a complete answer that gets your code to run like it's supposed to would mean writing most of your code, I won't go that way. Instead, you should apply one of the most powerful debugging methods known to humans and do it yourself:
https://en.wikipedia.org/wiki/Rubber_duck_debugging
Good luck and enjoy ;)
I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here