This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.
my current code:
switch (studentMenu) {
case 1: // Change all four fields
System.out.println("Please enter in a first name: ");
String firstNameIntermediate = scan.next();
firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1);
System.out.println("Please enter in a middle name");
middleName = scan.next();
System.out.println("Please enter in a last name");
lastName = scan.next();
System.out.println("Please enter in an eight digit student ID number");
changeID();
break;
case 2: // Change first name
System.out.println("Please enter in a first name: ");
firstName = scan.next();
break;
case 3: // Change middle name
System.out.println("Please enter in a middle name");
middleName = scan.next();
break;
case 4: // Change last name
System.out.println("Please enter in a last name");
lastName = scan.next();
case 5: // Change student ID:
changeID();
break;
case 6: // Exit to main menu
menuExit = true;
default:
System.out.println("Please enter a number from 1 to 6");
break;
}
}
}
public void changeID() {
studentID = scan.next();
}
I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX methods.
Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
Please enter letters:
&###$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int, use hasNextInt() and then nextInt().
Related questions
Validating input using java.util.Scanner - has many examples!
It's probably easiest to do this with a regular expression. Here's some sample code:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
System.out.println(isNumeric("123"));
System.out.println(isNumeric("abc"));
System.out.println(isNumeric("abc123"));
System.out.println(isAlpha("123"));
System.out.println(isAlpha("abc"));
System.out.println(isAlpha("abc123"));
}
private static final Pattern NUMBERS = Pattern.compile("\\d+");
private static final Pattern LETTERS = Pattern.compile("\\p{Alpha}+");
public static final boolean isNumeric(String text)
{
return NUMBERS.matcher(text).matches();
}
public static final boolean isAlpha(String text)
{
return LETTERS.matcher(text).matches();
}
}
You should probably write methods of "getAlphaInput" and "getNumericInput" which perform the appropriate loop of prompt/fetch/check until the input is correct. Or possibly just getInput(Pattern) to avoid writing similar code for different patterns.
You should also work out requirements around what counts as a "letter" - the above only does a-z and A-Z... if you need to cope with accents etc as well, you should look more closely at the Pattern docs and adapt appropriately.
Note that you can use a regex to validate things like the length of the string as well. They're very flexible.
Im not sure this is the best way to do, but you could use Character.isDigit() and Character.IsLiteral() mabybe like this:
for( char c : myString.toCharArray() ) {
if( !Character.isLiteral(c) ) {
//
}
}
try regexp: \d+ -- numerical, [A-Za-z]+ -- alphabetical
I don't think you can prevent the users from entering invalid values, but you have the option of validating the data you receive. I'm a fan of regular expressions. Real quick, something like this maybe (all values initialized to empty Strings):
while (!firstName.matches("^[a-zA-Z]+$")) {
System.out.println("Please enter in a first name");
firstName = scan.next();
}
...
while (!studentID.matches("^\\d{8}$")) {
System.out.println("Please enter in an eight digit student ID number");
changeID();
}
If you go this route, you might as well categorize the different cases you need to validate and create a few helper methods to deal with each.
"Regex" tends to seem overwhelming in the beginning, but learning it has great value and there's no shortage of tutorials for it.
That is the code
public class InputLetters {
String InputWords;
Scanner reader;
boolean [] TF;
boolean FT;
public InputLetters() {
FT=false;
while(!FT){
System.out.println("Enter that you want to: ");
reader = new Scanner(System.in);
InputWords = reader.nextLine();
Control(InputWords);
}
}
public void Control(String s){
String [] b = s.split(" ");
TF = new boolean[b.length];
for(int i =0;i<b.length;i++){
if(b[i].matches("^[a-zA-Z]+$")){
TF[i]=true;
}else
{
TF[i]=false;
}
}
for(int j=0;j<TF.length;j++){
if(!TF[j]){
FT=false;
System.out.println("Enter only English Characters!");
break;
}else{
FT=true;
}
}
}
Related
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
Essentially the idea of this program is to test user input and throw exceptions that I've created when invalid data is entered. For example: name cannot be empty and must be all alpha characters (no special or numeric). I have embedded this in a do-while loop that will continue so long as q is not entered to quit. I'm reading in the user input via scanner line and then sending the string inputted to a function that validates whether it meets the criteria. If it does not, then the function throws my custom exceptions. It all works fine EXCEPT when the exception is thrown it still takes that string and puts it in the new Person object.
How do I throw the exception to the user but THEN require them to re-enter the name or age until it's entered correctly?
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter person info or q to quit.");
System.out.print("Please enter the name of this person:");
String name = input.nextLine();
if(name.equalsIgnoreCase("q"))
{
break;
}
try{
isName(name);
}catch (InvalidNameException n){
System.out.println(n);
}
System.out.print("Please enter an age for this person:");
String age = input.nextLine();
try{
isValidAge(age);
}catch(InvalidAgeException a){
System.out.println(a);
}
public static void isName(String name) throws InvalidNameException
{
if(name.isEmpty())
{
throw new InvalidNameException("You did not enter a name.");
}
String[] namez = name.split(" ");
for(int i=0;i<namez.length;i++)
{
char[] charz = namez[i].toCharArray();
for (char n : charz)
{
if(!Character.isLetter(n))
{
throw new InvalidNameException("You have entered an invalid name.");
}
}
}
}
Put a continue; in your exception handling. It will break the loop an reenters it.
I would assume that the error lies within the compatibility of your isName() method and the method loop shown. It probably happens after it sets the name to a variable too. I cant tell you anything really specific because I cant see the isName method though.
The easiest way I know of doing this is to validate the obtained String using a regular expression. You can do something like this:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
String regex = "[A-Z a-z]+(\\s)[A-Z a-z]+";
System.out.println(name.matches(regex)? "matches": "does not match");
The expression regex is used to evaluate a sequence of alpha characters (no numbers or special characters) separated by a space. So, something like: "Joe Smith" will pass validation, but something like "Joe 123Klkjsd" will not.
You can take this code and test the input String in a while() loop:
while(!name.matches(regex))
{
// Prompt the user to re-enter a valid name and assign to name variable
}
Something like that should work.
It would be better to evaluate each variable within a do-while loop. Thus if there is an error in the variable age would not necessarily re-enter the name.
Scanner input = new Scanner(System.in);
String name;
String age;
System.out.println("Enter person info or q to quit.");
do{
System.out.print("Please enter the name of this person: ");
name = input.nextLine();
if(name.equalsIgnoreCase("q")) break;
try{
isName(name);
break;
}catch (InvalidNameException n){
System.out.println(n);
continue;
}
} while (true);
if(!name.equalsIgnoreCase("q"))
do{
System.out.print("Please enter an age for this person: ");
age = input.nextLine();
if(age.equalsIgnoreCase("q")) break;
try{
isValidAge(age);
System.out.printf("Nombre; %s\nEdad: %s",name,age);
break;
}catch (InvalidAgeException a){
System.out.println(a);
continue;
}
} while (true);
for the last few hours i've been trying to get this code to only allow character input, as its for accepting names..
I have been following the same type of method i used to allow only integers, but with no luck.
any advice would be great,
Here is my code
String name;
System.out.println("Enter student's name: ");
name = in.nextLine();
while (!in.nextLine().matches("[a-zA-Z]"));
{
System.out.println("Please enter a valid name!: ");
in.next();
}
name = in.nextLine();
Your regex checks if the line matches exactly one [a-zA-Z] character. You probably want to check at least one: [a-zA-Z]+
Bear in mind that the way you are checking, you won't get what you have checked in the variable name, as you are consuming it in your checking. Can I propose an alternative:
System.out.println("Enter student's name: ");
String name = in.nextLine();
while(!name.matches("[a-zA-Z]+")){
System.out.println("Please enter a valid name!");
name = in.nextLine();
}
I'm not too familiar with regex, personally, so I would just go with a method that takes a string and determines whether it is only comprised of the alphabets.
[EDIT] Shame on me, the method for testing if a character is a letter is static. Thanks to dansalmo for reminding me.
public static boolean isAlphabetic(String s) {
for(int i = 0; i < s.length(); i++) {
if (!Character.isLetter(s.charAt(i))) return false;
}
return true;
}
Did you check the value of the variable name?
While you assign the input to name , you seem to read the next line for regex check.
Remove the in.next too and it should work fine
Similar to Bucco's solution but iterating over a char array:
public static boolean isAlphabetic(String s) {
for(char c : s.toCharArray())
if (!Character.isLetter(c)) return false;
return true;
}
For my project I need to input a first and last name with no numbers but I simply can't find anything online. If you could help, that would be terrific.
Also if you have the time, I need to flip the first and last name with a comma when the user inputs them.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class PhoneListr {
public static void main (String[] args) throws IOException {
String firstName;
String lastName;
System.out.println ("Please enter your first name:");
firstName = PhoneList ("");
System.out.println ("Please enter your last name:");
lastName = PhoneList ("");
System.out.println ("Your full name is: " + lastName + "," + firstName);
}
public static String PhoneList (String input) throws IOException {
boolean continueInput = false;
while (continueInput == false) {
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (System.in));
input = bufferedReader.readLine();
continueInput = true;
if(input.matches("[a-zA-Z]+")) {
continueInput = true;
}
else {
System.out.println ("Error, you may only use the alphabet");
continueInput = false;
}
}
return input;
}
}
use String.matches(regex):
if(input.matches("[a-zA-Z]+")) {
System.out.println("your input contains no numerics");
}
else {
System.out.println("only alphabets allowed");
}
the above regex checks a through z, or A through Z, inclusive (range).
For this type of string matching you need to use Regular Expressions, or "RegEx"es. It is a very big topic to cover but here's an introduction. RegExes are tools used to test whether strings match certain criteria, and/or to pull certain patterns out of that string or replace certain parts that match those patterns with something else.
Here is an example using a RegEx to test whether your input contains a digit:
if(input.matches("\\d")) {
// matched a digit, do something
}
Based on OP problem and clarification here are few suggestions.
Chaitanya solution handles the check for only alphabets perfectly.
About the neglected areas of problem :
i would advice you to make two variable firstName and lastName inside the main()
String firstName;
String lastName;
Change retun type of method phoneList() to String
return the entered name input insted of number inside the method phoneList ( dont actually see why you are returning number) and store it inside the firstName and lastName
System.out.println ("Please enter your first name:");
firstName = PhoneList (0);
System.out.println ("Please input your last name:");
lastNamr =PhoneList (0);
now to print it in the "comma format" use
System.out.println("full name is: " +lastName+ "," +firstName);
As i read your program again , its a mess!!
About the method phoneList()
Use regex condition to set continueInput to true/flase and not exploit execptions.
P.s. I would appreciate "editing" to post , if any fellow member find any mistakes above, using a mobile, not sure about formatting etc. Thanks. :-) (y)
You can also use
if(input.matches("[^0-9]"))
{
System.out.println("Don't input numbers!");
continueInput = false;}
Can't understand what 2nd question asks. For answer what I get from your 2nd question is like this.
In main function change the code like this
String first_name = null;
String last_name = null;
System.out.println ("Please enter your first name:");
first_name = PhoneList();
System.out.println ("Please input your last name:");
second_name = PhoneList();
System.out.println (second_name+","+first_name);
then in PhoneList function last line should be changed to
return input;
Please check for a link! for more info
You can add a check by passing the argument to method StringUtils.isNumeric
This returns true if the String entered is numeric
I am trying to replace a specific character '8' with a '2' in a string. I think I have everything set up correctly and when I look online for examples, this looks like it should. When I print the string though, it is just as I entered it. To run it, test it with "80802" or some similar input. Thanks!
import java.util.Scanner;
class PhoneNumber {
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number.replace('8', '2');
System.out.println("Your number is: " + number );
}
}
A common mistake... You want:
number = number.replace('8', '2');
String.replace() doesn't change the String, because Strings are immutable (they can not be changed). Instead, such methods return a new String with the calculated value.
number.replace() returns a new string. It does not change `number'.
number.replace('8','2'); returns the correct string it does not modify number. To get your desired functionality you must type
number = number.replace('8','2');
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number = number.replace('8', '2');
System.out.println("Your number is: " + number );
}
Hope this helps.