Restrict user to input numbers - java

`Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String userName = scanner.nextLine();
if (scanner.hasNextDouble()){
System.out.println("You can't enter numbers");
}`
Here i can't print "You can't enter numbers". Or is there any other option to restrict user to input numbers?

You can try out something like below
public static void main(String[] args) {
boolean validUsername = false;
String regexForNumbers = ".*\\d.*";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
while (!validUsername) {
String userName = scanner.nextLine();
if(userName.matches(regexForNumbers)){
System.out.println("Username Can not contain numbers");
System.out.println("Please Enter username again:");
}else{
validUsername = true;
}
}
}
Here String regexForNumbers = ".*\\d.*"; will check whether the username contains a number,and you can expect something like this,
Enter your name:
maneesha123
Username Can not contain numbers
Please Enter username again:
123
Username Can not contain numbers
Please Enter username again:
maneesha

Keep it simple, use the String#matches() method with a small Regular Expression (regex) to make sure numerical digits have not been supplied. The "\\D" regex does exactly that, for example:
Scanner scanner = new Scanner(System.in);
String userName = "";
while (userName.isEmpty()) {
System.out.println();
System.out.print("Enter your User name: --> ");
userName = scanner.nextLine();
// Anything is acceptable 'except' numerical digits.
if (!userName.matches("\\D+")) {
System.err.println("Invalid name supplied (" + userName + ")!.\n"
+ "Numerical digits are not permitted! Try again...");
userName = "";
}
}
System.out.println("Acceptable: " + userName);

Related

String input exceptions java

I'm trying to use try and catch exceptions in case the user does not enter strings for username and integers for the pin code. but my code it's not working
this is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
try {
String username = myuser.nextLine();
System.out.println("Your username is: " + username);
}
catch( Exception e) {
System.out.println("Incorrect username! ");
}
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}
}
I tried to enter integers at the username to see if my try catch code works but the code doesn't recognize it as a problem.
Enter your username:
234
Your username is: 234
Enter your pin code:
As I understand it, you want to check if your inputs are valid.
For username, nextLine() reads the given input as String, therefore, you can enter anything and it will be read as a string. Entering 123 as an input will be read as "123" and it won't throw any exceptions. If you want to check if the input string is alphabetic, i.e., contains only letters, you can refer to Check if String contains only letters
For pin code, you can check it with a try/catch block like this:
System.out.println("Enter your pin code: ");
try {
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
} catch(InputMismatchException e) {
System.out.println("Incorrect pin!");
}
It will check if the given pin code is a Java Integer, please note that given input can be a negative integer, and you should check it if you need to.
Unfortunately the command line and Scanner has no validation; has no Exceptions.
String username = "";
do {
System.out.println("Enter your username:");
username = myuser.nextLine();
} while (username.isEmpty());
int pin = -1;
do {
System.out.println("Enter your pin code: ");
if (myuser.hasNextInt()) {
pin = myuser.nextInt();
} else if (myuser.hasNext()) {
myuser.next();
System.out.println("You must enter digits for the pin code.");
}
myuser.nextLine();
} while (pin == -1);
As you see Scanner.hasNextInt() should be queried, to check that an integer was provided. Any other non-numeric token could be consumed with next().
You could also use myuser.hasNextLine() when the typing user broke out of inputting.
This makes the use of Scanner circumstantial. I prefer reading lines and parsing them, say with Integer.parseInt(line). Otherwise I strongly advise to use the Console class which even has password entry (so the PIN does not show on the screen). This class however cannot be tested inside the IDE as a "console" in the IDE generally does a System.setIn(...) to capture the console. Console has nice prompts.
// SAMPLE CODE
char[] passwd;
Console cons = System.console();
if (cons != null) {
String username = cons.readLine("User: ");
passwd = cons.readPassword("Password for %s: ", username);
if (passwd != null) {
...
Arrays.fill(passwd, ' '); // Clear sensitive data in memory.
}
}
As you have seen from other answers everything read from the scanner will be read as a String. Here is a little trick or workaround to check if someone enters a number.
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = myuser.nextLine();
try {
int valueInInteger = Integer.parseInt(username);
System.out.println("Incorrect username! ");
} catch (NumberFormatException e) {
System.out.println("Your username is: " + username);
}
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}
The trick here is if you parse a string it will throw a number format exception and you will be sure its a string.
Try the follow code, maybe you can use.
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = myuser.nextLine();
boolean isNumeric = username.matches("[+-]?\\d*(\\.\\d+)?");
if (isNumeric){
System.out.println("Retry! Incorrect username!");
main(args);
System.exit(0);
}
System.out.println("Your username is: " + username);
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}

How can I get multiple user inputs and save their value? [duplicate]

How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now

Create password for user that consists of surname written backwards, followed by a star, age, then a star, then first name written backwards

public static void main(String[] args)
{
String firstName = "";
double age =0;
String surname ="";
String password ="";
Scanner scan = new Scanner (System.in);
System.out.println("Please enter your first name:");
firstName= scan.nextLine();
System.out.println("Please enter your age:");
age=scan.nextDouble();
System.out.println("Please enter your surname:");
surname= scan.nextLine();
System.out.println("Please enter your password:");
password=scan.nextLine();
}
Do i create another variable for surnameBackwards?
Something like this:
String surnameBackwards = StringUtils.reverse(surname) + "*" + age + "*" + StringUtils.reverse(firstName)

Validate input word using Scanner.hasNext()

I've been reading validation for user input if it is not a number or if input isn't a character, but how do I check if the user input is something I defined for them?
System.out.println("What meal would you like to eat?"
+ " (appetizer, soup, salad, main, or dessert)");
String meal = console.next();
I saw
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
but compiler does not like when i change
(!sc.hasNext("[aeiou]"))
to
(!sc.hasNext("[appetizer, soup, salad, main, dessert]"))
Maybe you want to try it this way (you also can use enums instead of a HashSet):
System.out.println("What meal would you like to eat?"
+ " (appetizer, soup, salad, main, or dessert)");
HashSet<String> vowels = new HashSet<String>();
vowels.add("appetizer");
vowels.add("soup");
vowels.add("salad");
vowels.add("main");
vowels.add("dessert");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (sc.hasNext()) {
String vowel = sc.next();
if (vowels.contains(vowel)) {
System.out.println("That's a vowel!");
} else {
System.out.println("That's not a vowel!");
}
}
You can do as follows. Check if the user's input is inside an array of permitted values.
List<String> meals = Arrays.asList(
new String[]{"appetizer", "soup", "salad","main","dessert"});
String meal = console.next().toLowercase();
if(meals.contains(meal)){
//Do what you want with correct input.
}

How to accept enter as valid input to Scanner.nextLine()?

I just want the scanner to read new line as empty string then continue to next process if the user press enter. So valid input must be y,n,enter. Any idea how to do this?
This is my code:
String gender = "", employed = "";
Scanner in = new Scanner(System.in);
System.out.print("Gender M/F, press enter to skip... ");
while(!in.hasNext("[mfMF]$")){
System.out.print("Invalid, please choose m/f only... ");
in.nextLine();
}
if(in.hasNextLine()){
gender = in.nextLine();
}
System.out.print("Employed? y/n, press enter to skip... ");
while(!in.hasNext("[ynYN]$|")){
System.out.print("Invalid, please choose y/n only... ");
in.nextLine();
}
if(in.hasNextLine()){
employed = in.nextLine();
}
System.out.println(gender + " : " + employed);
Try This :
import java.util.*;
class Scanner1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s;
do
{
s=sc.nextLine();
if(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")))
{
System.out.println("Please Enter valid input");
}
}while(!(s.equalsIgnoreCase("y")||s.equalsIgnoreCase("n")||s.equalsIgnoreCase("")));
}
}
So, to check if the user has pressed enter, you would have to make use of the isEmpty() method. The way to do that is shown below:
String enter = in.nextLine();
if (enter.isEmpty()) {
// do what is needed
}

Categories

Resources