Make a loop AND catch using Strings instead of ints? (java) - java

I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}

Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}

You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}

Related

How would I make it so that whenever a non-integer value is entered, it will tell the user to enter an integer value? Java - NetBeans

I'm making a very simple program that asks a user to input an age and then it will calculate a charge for admission. So far all works well but I'm wanting to add a check in so that if the user inputs anything other than an int value, it will ask them to enter an int value. I.e if they enter a character.
Here is my code:
public class CalcChargeAge {
public static void main(String[] args) {
int x;
double chargeA = 20;
double chargeB = 10;
System.out.println("Enter Users age to calculate charge for entry. ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x >= 18) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeA);
} else if (x >= 12) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeB);
} else {
System.out.println("Users age is " + x);
System.out.println("User entry charge is free. Print admission ticket.");
}
}
}
You can use the Scanner.hasNextInt() method to check whether the input is an integer, which I think is a lot nicer than catching an exception.
Then for the full implementation you could wrap everything in a loop, so you could do something like:
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
if(in.hasNextInt()) {
int x = in.nextInt();
// Handle input
break;
}
else {
// Handle invalid input
in.next();
}
}
Something like this should work fine:
boolean isValid = false;
int validInput = 0;
while (!isValid) {
try {
validInput = scanner.nextInt();
isValid = true;
}
catch (Exception e) {
System.out.println("Please enter a valid integer.");
}
}
// ... code using validInput
One of the ways (beware, it might not be the best or even the good one) to go about it would be to replace x=in.nextInt(); with
while(true) {
String input = in.next();
try {
x = Integer.parseInt(input);
break;
} catch (Exception e) {
System.out.println("Please provide an integer!");
}
}
this will not leave the loop until user provides an integer value (evil!)

How can I handle input string, during the process of if, else if, else including Integer.parseInt?

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

how do i do input validation inside a try and catch block?

i have a program where user can enter their name and stuff. its isnised a big try bracket. then at the end it has a catch when the user enter letters instead of number therell be warning "invalid input" i wanna make it so if its invalid 3x, the program closes
so far i have this. i ommited some of the unnecesarry codes, but the important part is just the try, and do while loop
public static void main(String[] args) throws FileNotFoundException {
try{
Scanner input = new Scanner(System.in);
String input_option = "1";
// calling option method
print_options();
int attempt= 0;
boolean authenitcated = false;
do{
input_option = input.nextLine();
if (input_option.equals("0")) {
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
type.println("Annual Income: " + income);
type.println("Tax: " + opt0tax);
myfile.exists();
type.close();
}
else if (input_option.equals("1")) {
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
type.close();
}
else if (input_option.equals("2")) {
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
myfile.exists();
type.close();
}
//extra_options();
input.close();
catch(InputMismatchException exi){
System.out.println("you must enter a double");
attempt++;
}
}while(attempts < 3 && authenticated == false)
}
You need to add an else, at the bottom of your options select part.
Good practise would be to cast it to int, because user can enter zero with lead space, which is still valid.
Secondly close the file after the catch in finally block (close all closeable resources)
int attempt = 0;
boolean authenticated = false;
do {
input_option = input.nextLine();
try {
Integer option = Integer.valueOf(input_option);
switch (option) {
case 0:
System.out.println("Enter your first name ");
String firstnameopt0 = input.nextLine();
System.out.println("Enter your last name ");
String lastnameopt0 = input.nextLine();
break;
case 1:
System.out.println("Enter your first name ");
String firstnameopt1 = input.nextLine();
break;
case 2:
System.out.println("Enter your first name ");
String firstnameopt2 = input.nextLine();
break;
default:
attempt++;
System.out.println("you must enter a int");
}
} catch (Exception ex) {
System.out.println("you must enter a int");
attempt++;
}
} while (attempt < 3 && authenticated == false);

I'm having trouble outputing the user's amount of guesses in a Hangman game

This is basically just a hangman project for my class and I'm not allowed to use arrays. The word is hidden with dashes to the user.The user has to pick a letter and the number of spaces they would like to check. The user has a certain amount of guess depending on the difficulty they choose. If the letter they guessed is in at least one of the spaces they chose then the user loses no guesses, if the letter they guessed is in none of the spaces they chose then the user loses a guess.
for example the output should look like
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
But it currently looks like this
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
Your letter was not found in spaces you provided
Guesses Remaining: 13
Your letter was not found in spaces you provided
Guesses Remaining: 12
Your letter was not found in spaces you provided
Guesses Remaining: 11
Here is what I have so far
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
for ( String a : spaces.split("\\s"))
{
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
In the example I used the difficulty was set to easy.
There is a bug here:
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
You cannot print the message directly because you need to make sure all spaces are not matched. This should be work:
public class HangmanBeta {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e")) {
guesses = 15;
}
if (diff.equalsIgnoreCase("i")) {
guesses = 12;
}
if (diff.equalsIgnoreCase("h")) {
guesses = 15;
}
if (testingMode == true) {
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while (!newWord.equalsIgnoreCase(guess))
innerloop:
{
while (true) {
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if (!Character.isLetter(letterInput.charAt(0))) {
System.out.println("Your input is not valid, try again");
break;
}
if (letterInput.equalsIgnoreCase("solve")) {
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord)) {
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
} else {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e")) {
if (amountOfSpaces != 7) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i")) {
if (amountOfSpaces != 5) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h")) {
if (amountOfSpaces != 3) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
int numSpacesLeft = spaces.split("\\s").length;
for (String a : spaces.split("\\s")) {
int x = Integer.valueOf(a);
if (x > guess.length()) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0)) {
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
numSpacesLeft--;
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0)) {
if (numSpacesLeft == 0) {
guesses = guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
}
if (guesses == 0) {
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess)) {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if (guesses == guesses - 1) {
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
Hop this could help you!

Java validating Scanner Input with

How would I use InputMismatchException to determine if the value entered into the Scanner is not an integer? Basically, if they enter in a word instead of an integer I need to use InputMismatchException to return a message.
while (true) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try{
Integer.parseInt(i);
} catch (InputMismatchException e) {
System.out.println("Sorry, " + i + " is not a number.");
}
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
Change your code as such:
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}
}
Changes:
Note use of nextLine(). This is because it seems you want to use the input as part of your error message, and nextInt() won't let you do that.
We can now move the i declaration inside the try block, along with
the code that uses it, so we won't issue "1 was not selected" when the input was "ssss" or whatever.
We use NumberFormatException, as that's what Integer.parseInt()
throws when it can't parse an integer from the String.
This is what i mean
while (true) {
Scanner sc = new Scanner(System.in);
int i = -1;
try
{
i = sc.nextInt();
}
catch (InputMismatchException e)
{System.out.println("Sorry, " + i + " is not a number.");}
if (i == 1)
System.out.println("1 was selected");
else
System.out.println("1 was not selected");
}
I am new to the programming, I think I got the code for your question.
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == parseInt(i, 3)) {
System.out.println(s+" is selected");
} else {
System.out.println("Input value is " + s);
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}}}
private static int parseInt(int i, int j) {
// TODO Auto-generated method stub
return 0;
}}
reference

Categories