Alternate method to .hasNextInt? [duplicate] - java

This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
I'm new to java and I'm wondering if there is a different method that I can use instead of has.nextInt() as this method messes up my scanner. For example
do {
System.out.println("Please enter your full name: ");
memberName = input.nextLine();
if (input.hasNextInt()) {
System.out.println("Your name cannot contain a number");
input.next();
} else {
successful = true;
}
} while (successful == false);
console
Create new member
Please enter your full name:
jack
jack
I have to enter my name twice before it moves on
I know theres questions out there like this but I've had no luck with any of there solutions. Thanks
EDIT
I'm trying to make sure that the input does not contain any number at all and if it does then
System.out.print("Your name cannot contain any numbers");
happens

The usage of if(input.hasNextInt()){ is wrong here. As you want to find numbers in your previous entered string which is memberName
You could use regex for this purpose:
Pattern digitPattern = Pattern.compile("\\d+");
And then you can use this to validate any string:
System.out.println(digitPattern.matcher("Marcinek 234").matches());

do {
System.out.println("Please enter your full name: ");
memberName = input.nextLine();
if (memberName.contains("1234567890")) {
System.out.println("Your name cannot contain a number");
} else {
successful = true;
}
input.next();
} while (successful == false);
You were using input in your if-statement to check, but you assigned memberName to the whole line.

Try creating your own method which will test if passed name is valid. It can look for instance like this:
private static boolean isValidName(String name){
return name.matches("[a-z]+(\\s[a-z]+)*");//can be optimized with precompiled Pattern
}
Now your code can look like:
System.out.println("Please enter your full name: ");
do {
memberName = input.nextLine();
successful = isValidName(memberName);
if (!successful) {
System.out.println("Your name is not valid. Valid name can contain only letters and spaces. No digits are allowed.");
System.out.println("Please try again: ");
}
} while (!successful);
System.out.println("welcome: "+memberName);

If you want just read line from user input you can use:
hasNextLine()
Or you can just use:
hasNext()
And try to change this:
while (successful == false);
With this:
while (successful);

You could use: enteredName.contains("1") to check for numbers.
For example:
boolean containsNumbers = false;
for(int i = 0; i<9; i++){
if (name.contains(""+i)) containsNumbers = true;
}

Related

input mismatch exception while using space in between words

I'm working on a project and I already finished it, I have really simple problem which makes me really confused. I'm trying to ask a user to enter a number from a menu and depending on that different things happen, but I get input mismatch exception whenever I type space in between words. I get that error on the last line of the code, please check my code below, Thanks.
System.out.println("Enter: " + "\n1.Enter Name" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
The issue is with your usage of Scanner#next(), in combination with wanting to input multiple "words" sepearted by a whitespace for example. (Disclaimer: I understand your question in the way that you want to enter multiple words for the "name" input, this answer takes that as a prerequisite)
See following excerpt from the Scanner#next() Javadoc:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace. So when you request a name from the user, and the user wants to enter "John Doe", only "John" will be read, and "Doe" will be left, most likely causing the error you are seeing.
The workaround I would propose is to use nextLine() to read the whole line while providing each input line by line.
However, be aware of this issue: Scanner is skipping nextLine() after using next() or nextFoo()?
Keeping that in mind, I would modify your code as follows:
String name = "";
String anotherName = "";
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
Sidenotes:
I moved the declaration of your name and anotherName variables, as they don't have to be re-declared everytime.
However you should actually do something with them (e.g. save them in a list, or create some object with them) otherwise they will be lost on the next loop iteration.
You can omit the check for if (userChoice == 3) since this would never happen in combination with the while (userChoice != 3).
Example input:
Enter:
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3

How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values.
but nothing works. Even with no entered values program goes further without printing my error. What am I doing wrong?
my code example
Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");
String newcomer = nameScan.nextLine();
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();
if (userName.length()==0) {
System.out.println(" ");
System.out.println("You have to set up a player name first... ");
System.out.println(" ");
}
else {...
As #11thdimension said, you have to validate the input.
You can do something like:
if (newcomer.isEmpty()) {
System.out.println("Please write something");
}
Or you can do a while loop and keep asking for a correct input.
Your code
if(username.length() == 0)
will not check whether the username contains space because space is counted towards the length of the String.
To check for empty String input(which may contain space(s)), you can do:
if("".equals(username.replaceAll("\\s+",""))) //or
if("".equals(username.trim()) //or
if(username.isEmpty())
Further more, you would want to use a do-while loop for validation instead of using an if-statement.

How to prevent user from entering white space or just hitting enter when a number is expected?

I'm trying to only accept numbers from a user. This code works for giving them an error message if they enter a letter. But it doesn't work for if they hit Enter or just white space. I've tried initializing a String called test as null and then setting scnr.nextLine() = test, and then checking if test is empty, but I didn't understand how to keep the rest of the program operating correctly when I did that. Scanner is very tricky to me. Please help!
double mainNumber = 0;
System.out.print("Enter a number: ");
if (scnr.hasNextDouble() ){
mainNumber = scnr.nextDouble();
System.out.println(mainNumber);
scnr.nextLine();
}
else {
System.out.println("Sorry, please enter a number.\n");
scnr.nextLine();
}
You have to use while-cycle and loop input as long as needed before user put a valid number.
This code
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double mainNumber = 0;
boolean isValidNumber = false;
System.out.print("Enter a number: ");
while (isValidNumber == false) {
String line = scnr.nextLine();
try {
mainNumber = Double.valueOf(line);
isValidNumber = true;
} catch (NumberFormatException e){
System.out.print("Sorry, please enter a number.\n");
}
}
System.out.println("Main number is: " + mainNumber);
}
Having this sample output :
Enter a number: sdfgsgxb
Sorry, please enter a number.
xcvbxcvb
Sorry, please enter a number.
gsfdfgsdf
Sorry, please enter a number.
aearg
Sorry, please enter a number.
15.77
Main number is: 15.77
Well I guess your code is in a while loop or something ? So that it keep asking until the user enter the right value.
Then you should (for convenience) use String str = scnr.nextString() instead of nextDouble() and analyze the string it returned.
You can use str.trim() to remove whitespaces (and then check if string is empty with str.isEmpty() ), and to check if it's a number you can use regexp ( How to check that a string is parseable to a double? and any regex tutorial you can find ) or just use this regex: str.matches("\\d+") (returns true if str is a number, but no comma here).
Of course, don't forget to cast your String as double after: Double.parseDouble( str.replace(",",".") );. I hope the "replace" part is obvious ;)
You might use the following snippet to read one double value:
Scanner scanner = new Scanner(System.in);
try {
double number = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}

Validation input to be string only and numbers only JAVA [duplicate]

This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 8 years ago.
I am a student and i have a little problem with validation inputs.
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
//If name contain other than alphabetical character print an error
double number;
System.out.println("Enter number:");
name = keyboard.nextDouble();
//If number contain other than number print an error
What i have tried is test to parse the string to double but i could not.
I have no idea how to test if the double is only number.
Please give me a clue of what i should do.
You can use Regular expression to check if the input match your constraint as follow :
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
if (!name.matches("[a-zA-Z_]+")) {
System.out.println("Invalid name");
}
String number;
System.out.println("Enter number:");
number = keyboard.nextLine();
if (!number.matches("[0-9]+")) {
System.out.println("Invalid number");
}
Here is a good tutorial to learn regex .
You can loop through each character of the String and check if it's not alphabetic using Character.isAlphabetic(char):
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name:");
String name = keyboard.nextLine();
for (char c : name.toCharArray()) {
if (!Character.isAlphabetic(c)){
System.out.println("INVALID");
break;
}
}
To only accept numbers, you can do something similar using the Character.isDigit(char) function, but note that you will have to read the input as a String not a double, or get the input as a double and the converting it to String using Double.toString(d).
double number = 0;
try {
number = Double.parseDouble(name)
} catch (NumberFormatException ex) {
System.out.println("Name is not a double.");
}
If number is not a double, you can catch a NumberFormatException.
It seems you are using scanner. If you are, you can use the Scanner class' hasNextDouble() to check if the input is a double before reading the double as shown below:
double number;
System.out.println("Enter number:");
if (keyboard.hasNextDouble()){
name = keyboard.nextDouble();
}
Have a look at the Scanner class docs for more information.
There is also the "fancier" regex solution.
Java Pattern Documentation
You can use this (untested code) given you used nextLine() for reading BOTH inputs:
boolean isWordOnly = Pattern.matches("\w*", name); //name is in your code
boolean isFloatOnly = Pattern.matches("\d*.?\d*", number); //number is in your code too
Now the too boolean values tell you if there is the desired format in your input. You can add it in a do - while loop or anything you want.
It is a good idea to start studying reg(ular) ex(presions) because they are useful in string formatting (Imagine that you have to test if the input is a valid email...). Also used to check for SQL injections and many key things in apps and programs generally.

Why is else statement a infinite loop?

I am fairly new to Java and I am trying to work on my data validation. The code runs fine when I use valid data, but when I put in a string instead of an integer the code just loops forever. It just loops the, "Bad input. Please enter a number." Thanks in advance!
//Get input from user
System.out.print("What is your name (Last, First)? ");
String name = scan.nextLine();
System.out.print("enter a date:");
String datein = scan.nextLine();
boolean valid = false;
while (valid != true)
{
System.out.print("Electricity used (KW):");
if (scan.hasNextDouble())
{
electricityUsed = scan.nextDouble();
valid = true;
}
else
System.out.println("Bad input. Please enter a number.");
}
because hasNextDouble always returns false.
here is the doc. You answer your own question :
but when I put in a string instead of an integer
To fix it add a scan.nextLine() to your else branch.
A simpler approach is to use the following.
System.out.print("Electricity used (KW):");
while(!scan.hasNextDouble()) {
scan.nextLine();
System.out.println("Bad input. Please enter a number.");
System.out.print("Electricity used (KW):");
}
double electricityUsed = scan.nextDouble();

Categories

Resources