I want to validate the user input before the program continued. For example:
A variable String name. The program displays 'Enter name' and if the user types in a number instead of a String, a message should pop up and also make the user assign a String to name.
This is what I have so far:
System.out.println("Enter name");
String name = input.nextLine();
I tried try/catch but that did not work. I tried using
if(input.hasNextInt()){System.out.println("Type in a string!");}
but that carries on through the program and still assigns a number to 'name'. It does not give the user a second chance to assign a string to 'name'
Here is something to get you started using regular expression. It only checks for a String with characters between A-Z and a-z. See what happens when you try and enter "FirstName LastName" and see if you can figure out how to fix it.
Scanner input = new Scanner(System.in);
String name;
while(true){
System.out.println("Enter name");
name = input.nextLine();
if (name.matches("[A-Za-z]+")){
break;
}else{
System.out.println("Please enter only letters");
}
}
System.out.println("Name selected: "+name);
The plus sign at the end of the brackets checks to see if you have at least one character. So if you enter a blank name, it will go to the else.
The number checking can be achived fairly simple with the String matches() method. This method tells whether or not the string matches the given regular expression.
String name = "Shrek";
if (name.matches(".*\\d+.*")) {
// Do whatever you want to do if the name contains a number
}
Try this solution that validate the input with pop up, when user inputs something invalid.
public class Test {
static String name;
public static void main(String[] args) {
final JFrame parent = new JFrame();
parent.pack();
parent.setVisible(false);
name = JOptionPane.showInputDialog(parent,
"Enter name", null);
while (true) {
if (name.matches("[A-Za-z]+")) {
break;
} else {
name = JOptionPane.showInputDialog(parent,
"Please enter only letters", null);
if (name.matches("[A-Za-z]+"))
break;
}
}
System.out.println("Name selected: " + name);
}
}
Related
What is the way to take some parameters as optional user input using java util Scanner? Below is my code. But, for all the parameters it's blocked till the user input is entered.
I want it to continue for second parameter in cases 'when the user input is entered and then pressed enter key' "OR" 'when just pressed enter key without entering any input'.
public class MainApplication {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter ordertypes in comma separated format (mandatory): " );
String orderOrActionTypes = in.next();
System.out.println("Enter orderAttributes (optional): " );
String orderAttributes = in.next();
System.out.println("Enter ActionAttributes (optional): " );
String actionAttributes = in.next();
}
}
You can still let the input but leave it empty.
When an input is required, the user can press Enter (which results on an empty string), and then you can test, whether the user typed something or not orderAttributes.isEmpty() and you do what you need based on the results.
Try using in.nextLine();, it may help.
I'm creating a program that prints user details, first the user inputs their details and then the program correctly formats the details and prints them inside a formatted box. I want the program to read strings and see if the users have entered invalid characters. For example the code below requests for the users first name:
// this code below is used to find the largest string in my program, ignore if this wont interfere
String fname = scan.nextLine(); //main scan point.
//below is used to calculate largest string inputted by the user.
int input = 0;
int fnamelength1 = fname.length();
input = fnamelength1;
int longest = 0;
if(input > longest)
longest = input;
If at this point the user enters #~~NAME~~# as their name, the program currently allows that... I want to make the program read what the user has inputted and print a message if their input isn't correct for example contains invalid symbols.
EDIT:
I'm considering anything other than characters in the alphabet as invalid... any numbers or symbols would therefore be invalid.
VALID:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Also valid:
' - .
This can be done using regular expressions with the String.matches method. Here you define a pattern and if the string matches your pattern then it can be considered valid:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = fname.matches("[^a-zA-Z'-]]");
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
EDIT
With String.matches we can't make a global search of invalid characters (what we want in this case). So is better using Matcher.find for this:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
Pattern pattern = Pattern.compile("[^a-zA-Z'\\-\\s]");
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = pattern.matcher(fname).find();
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
This time the pattern will validate any invalid character anywhere in the string.
One approach would be to use regular expressions, along with the String.matches() method.
As an example:
String fname;
... some code to get fname ...
boolean valid = fname.matches("[a-zA-Z]+");
valid should be true if and only if fname is a String containing alphabetic characters, and not empty.
If empty strings are also valid, then:
boolean valid = fname.matches("[a-zA-Z]*");
Look up the Java class Pattern for other variations.
package chapter6;
import java.util.Scanner;
public class formal_greeting {
public static void main(String[] args) {
String title;
String name;
String mr = null;
String miss = null;
String ms = null;
String mrs = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
name = input.next();
System.out.print("Enter your title: ");
title = input.next();
if (title.equalsIgnoreCase(mr)) {
System.out.println("Hello sir");
}else if (title.equalsIgnoreCase(miss)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(ms)) {
System.out.println("Hello ma'am");
}else if (title.equalsIgnoreCase(mrs)) {
System.out.println("Hello ma'am");
}else {
System.out.println("Hello " + name);
}
}
}
I can't figure out why my if statements won't work. so far it only displays (Hello "name") can someone please tell me what is wrong with my if statement???
Problem is not in the if statements.Change your method input.next() to input.nextLine() .Because using next() you will get only what you entered before the space. But if you use nextLine() the Scanner will read the entire input line.For more reference click here.
Hope this helps
You need to know the difference between a String variable and a string literal.
In your code, mr is a string variable. The value that it stores is null as you can see from this line:
String mr = null;
In the if statement, you test whether the user input is equal to the value string variable. Let's say you entered "Mr" in the console:
User input Value of the mr variable
"Mr" null
Are they the same? No.
The same goes for all the if statements. Finally the execution comes to the else and executes the stuff there since every if statement failed.
What you need to do is to use a string literal instead of a string variable.
A string literal is denoted by double quotes:
"This is a string literal"
So your if statements would look like:
if (title.equalsIgnoreCase("mr")) {
/* ⬆︎ ⬆︎
Quotes here!
*/
Alternatively, you can use variables as well. But you should not give them a value of null. Instead, give them a string literal:
String mr = "mr";
// etc.
This way, you don't need to change your if statement.
I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.
String validation issue:
This method works for the most part, but theres some apparent logic problem. If a user hits enter at the console with no input, it should return the "Error! this entry required" message, but it doesnt. I would have imagined it would, since I am testing for an input of
one or less chars
public String getChoiceString(String prompt, String s1, String s2) {
this.println(prompt);
String userChoice = this.sc.next();
String i;
boolean isValid = false;
while (isValid == false)
{
if (userChoice.equalsIgnoreCase(s1) || userChoice.equalsIgnoreCase(s2))
{
isValid = true;
}
else if (userChoice.length() <= 1 || userChoice.equalsIgnoreCase("")) {
System.out.println("Error! This entry is required. Try again.");
userChoice = this.sc.next();
}
else {
this.println("Error! Entry must be " + s1 + " or " + s2 + ". Try again.");
userChoice = this.sc.next();
}
}
return userChoice;
From here I create an instance of the class which contains this method. It is called console. I call the methods from this:
public class ConsoleTestApp {
public static void main(String[] args) {
System.out.println("Welcome to the Console Tester application");
System.out.println();
//get console object
Console console = IOFactory.getConsoleIO();
console.println("Int Test");
console.getIntWithinRange("Enter an integer between -100 and 100: ", -100, 100);
console.println();
console.println("Double Test");
console.getDoubleWithinRange("Enter any number between -100 and 100: ", -100, 100);
console.println();
console.println("Required String Test");
console.getRequiredString("Enter your email address: ");
console.println();
console.println("String Choice Test");
console.getChoiceString("Select one (x/y): ", "x", "y");
}
}
It doesn't seem like much of anything happens when you just enter a carriage return with Scanner#next. The Javadoc mandates that it only matches on a complete token with its delimiter.
The default delimiter for Scanner is \p{javaWhitespace}+. In essence, it describes a whole token as having at least one whitespace character in it.
Now, let's inspect the empty String. It doesn't contain any character in it. So, if we were going to match against the default delimiter regex, we would fail:
Scanner sc = new Scanner(System.in);
Pattern ptn = sc.delimiter();
System.out.println(ptn);
String empty = "";
String regex = "\\p{javaWhitespace}+";
System.out.println(empty.matches(regex)); // prints false
So, the pattern doesn't match, and the Scanner will block until it matches something, like A phrase.
So, instead of trying to deal with any headache that may be induced from next(), what you may be looking to use instead is nextLine(). In most cases, you want to use nextLine() when you want to match the entire line of entry, and next() when you're processing multiple elements in a single line.
String userChoice = this.sc.nextLine(); // wherever this Scanner instance lives...
This will match on anything containing a line separator, and since hitting return/enter will produce that, it will match the entire line you enter, even if it's a blank line.