I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.
Related
I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}
I am creating a user interface via command line that will ask for options from 1 - 4 and I want error checking. Only an integer between 1 - 4 is allowed. This is the code I have so far. I want the method to return the userInput integer to another method that will do some stuff with it.
package contactmanager;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author andyjohnson
*/
public class UserInterface {
public static Integer GetInput() {
Scanner in = new Scanner(System.in);
//Integer userInput;
System.out.println("Welcome to the contact manager\nMake a selection below:");
System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
try {
Integer userInput = in.nextInt();
if (userInput < 1 || userInput > 4) {
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
} catch (InputMismatchException e) {
e.getMessage();
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
return userInput;
}
}
My return statement is underlined in the IDE and is telling me it isn't initialized. I want to initialize it globally but allow the try statement to change the value. I've tried this.userInput = userInput but I can't figure out where my scope is broken. How do I give the try block global scope? I'm new to java, so anything is helpful. Thanks!
You can just declare userInput variable outside the try-catch block:
package contactmanager;
import java.util.InputMismatchException;
import java.util.Scanner;
public class UserInterface {
public static Integer GetInput() {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the contact manager\nMake a selection below:");
System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
Integer userInput = null;
try {
userInput = in.nextInt();
if (userInput < 1 || userInput > 4) {
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
} catch (InputMismatchException e) {
e.getMessage();
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
return userInput;
}
}
The try-catch block has a scope that is dissimilar to just writing code in-line with the rest of the method.
I think the problem you are having is in this line where the variable userInput is first declared inside the try-catch block:
Integer userInput = in.nextInt();
The reason why this is an issue:
Consider if the try-catch block failed. What would then be returned? The variable userInput hasn't even been defined, so Java would have no idea what to return.
The fix is relatively simple. You want to just move it out of the try-catch block, like so. That should get rid of your return error. I noticed you commented this change out. Why?
But I have an additional suggestion. Why are you calling UserInterface.GetInput()? Why not have the method accept the parameter of the valid input and simply don't call it when the data is not formatted appropriately? Do you use it? This would take away the need of a truly global-scoped variable.
Because of how this method is written, it must return an Integer of some kind, unless you write it should that the method throws an exception that is caught somewhere downstream.
I tried to make some fixes I think would make the most sense:
Scanner in = new Scanner(System.in);
Integer userInput; // Integer representation of user input
try {
Integer a = in.nextInt(); // if a can be assigned to an Integer this line work
if (a < 1 || a > 4) {
// called if the input can be assigned to an Integer and is within the range
userInput = a;
}
} catch (InputMismatchException e) {
// otherwise the catch block is called
System.out.println("Please enter a valid selection");
}
return userInput;
Maybe you want to call UserInterface.GetInput() inside the range check? Hope this helps!
Edit: Using a sentinel flag instead of recalling the method
Scanner input = new Scanner(System.in);
System.out.println("Please enter a valid Integer. When done type DONE ");
// this method will keep cycling until the String DONE is typed
// you could make this condition whatever you want
while (!input.hasNext("DONE")) {
String a = input.next(); // gets the next item from the Scanner
try {
Integer b = Integer.parseInt(a); // tries to 'cast' the String to an Integer
if (b < 1 || b > 4) {
System.out.println("Input is valid!");
} else {
System.out.println("Input is invalid!");
}
} catch (NumberFormatException e) {
System.out.println("Please enter a valid selection!");
}
}
I need to add a method to my guessing game that i made a while ago. The method should return the value they enter but should use a loop to require re-entry until one of those two values has been specified.
Also if the user inputs a word and not an int, it should ask for a number. I know that I will need to use a string instead of an int. I'm just having trouble figuring this out. Here is what I have so far:
import java.util.Random;
import java.util.Scanner;
class GuessNumber {
static Random rand = new Random();
static Scanner scan = new Scanner(System.in);
static int number;
public static void main(String[] args) {
playGame();
}
public static void playGame() {
number = rand.nextInt(100) + 1;
System.out.println("Guess the number between 1 and 100");
while (true) {
int guess = scan.nextInt();
if (guess < number) {
System.out.println("Higher!");
} else if (guess > number) {
System.out.println("Lower!");
} else if (guess == number) {
System.out.println("Correct!");
Scanner scan2 = new Scanner(System.in);
System.out.println("do you wanna play again?[Y/N]");
String val = scan2.next();
if (val.equalsIgnoreCase("Y")) {
playGame();
} else {
break;
}
}
}
}
}
There might be a better way to do it but try something along the lines of:
String input = scan.next();
int guess;
try{
guess = Integer.parseInt(input);
//rest of the code inside while(true) loop
}
catch(Exception e){
System.out.println("You need to enter a valid number.");
}
and then for the Y/N validation:
String val = "No";
Scanner scan2 = new Scanner(System.in);
do{
System.out.println("do you wanna play again?[Y/N]");
val = scan2.next();
}
while(!val.equalsIgnoreCase("Y") && !val.equalsIgnoreCase("N"))
if (val.equalsIgnoreCase("Y")) {
playGame();
break;
} else {
break;
}
Reasoning: You will get an error if they do not enter a valid number so you need to catch the error and let them know what is wrong. I like to get input as string and try to convert it to integers. As for the do/while section... Unless they enter Y or N it will keep asking them. Once out of the loop, if the input was "Y" it will call the playGame() again and then break after it finishes (basically whenever the user types n in the next game). If it wasn't "Y" then it had to be "N" and needs to break.
Let me know if this helps. I have the full code that will work but this should be easy enough for you to implement.
When you declare your static variables, put:
static int number, guess;
To declare both numbers at the same time. Then, inside the main loop, do the following:
while (true) {
while (true) {
try {
guess = Integer.parseInt(scan.nextLine());
break;
} catch (Exception e) {
System.out.println("Not a valid number!");
continue;
}
}
//Rest of your if's, else if's, etc
}
I've tested it, and it works for me.
If you need me to I can paste in all the code, but you should be able to just nest that second while loop inside the first, before the if statements, easily enough.
I had a bit of a hard time figuring this part out for a school project of mine.
So looking for a bit of clarification.
Generally, the user had to input a number (column) to insert a game piece.
However, if the user were to enter "q" the program would close down.
We were pointed into the direction of using "parseInt", however i am looking for a bit of clarification as to how this works?
while(response.equalsIgnoreCase("q"));
{
System.out.println("Do you want to play again?");
response = scan.next();
}
System.out.println("Do you want to play again?");
response = scan.next(); // this revisits the while loop that
// prompted the player to play.
import java.util.Scanner;
public class ScanInteger {
public static void main(String...args)throws Throwable {
int num = 0; String s= null;
System.out.print("Please enter a number : ");
Scanner sc = new Scanner(System.in);
do{
try{
s = sc.next();
num= Integer.parseInt(s);
System.out.println("You have entered: "+num+" enter again : ");
}catch(NumberFormatException e){
if(!s.equalsIgnoreCase("q"))
System.out.println("Please enter q to quit else try again ==> ");
}
}while(!s.equalsIgnoreCase("q"));
sc.close();
}
}
See http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public static int parseInt(String s)
throws NumberFormatException
You want to apply a try-catch block around the Integer.parseInt(userInput) call to catch a NumberFormatException
In the catch body, you can set a flag that the input was invalid. Put the whole thing in a while loop based on the boolean isInputIsValid.
boolean isValidNumber = false, wantsToQuit = false;
while (!isValidNumber) {
// Ask user for a value any way you want and save it to userInput
String userInput = "";
try {
Integer.parseInt(userInput);
isValidNumber = true;
} catch (NumberFormatException e) {
isValidNumber = false;
if (userInput.equals("q")) {
wantsToQuit = true;
break;
}
}
}
wantsToQuit is not a necessary variable, just showing what the purpose of that section is
I have been trying to stop the exceptions but I cannot figure out how.
I tried parseInt, java.util.NormalExceptionMismatch etc.
Does anyone have any insight how to fix this problem? Formatting is a bit off due to copy and paste.
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
if (!intFind.hasNextInt())
intFind.next();
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
}
}while(select < 0)
Other methods I have tried :
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
{
try{
select = intFind.nextInt();
}catch (java.util.InputMismatchException e)
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
return;
}
}
}while(select < 0)
It seems to me that you want to skip everything until you get an integer. This code here skips any input except an integer.
As long as there is no integer available (while (!in.hasNextInt())) discard the available input (in.next). When integer is available - read it (int num = in.nextInt();)
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt()) {
in.next();
}
int num = in.nextInt();
System.out.println("Thank you for choosing " + num + " today.");
}
}
Quick sample of how to catch exceptions:
int exceptionSample()
{
int num = 0;
boolean done = false;
while(!done)
{
// prompt for input
// inputStr = read input
try {
num = Integer.parseInt(inputStr);
done = true;
}
catch(NumberFormatException ex) {
// Error msg
}
}
return num;
}
IMO, the best practice is to use nextLine() to get a String input, then parseInt it to get the integer. If unparsable, just complain back to the user and request re-entry.
Remember you may have to do a second nextLine() (discard the input) to clear up the buffer.