Basically I want the user to enter a code in this format - XXXX000 and if the user enters 3 letters and 4 digits for example - it outputs an error.
What i did is that i wrote a command that input has to be maximum 7 characters but it doesn't specify what the characters need to be. Therefore if user enters 7 digits, it is still accepted which it should not.
System.out.print("Enter the animal's unique code - Format: (XXXX111)");
String codein = in.nextLine();
a.setCode(codein);
if (codein.length() != 7) {
System.out.println("Format was not met, please try again");
System.out.println("Enter the animal's unique code - Format: (XXXX111)");
codein = in.nextLine();
a.setCode(codein);
}
An error should appear if user does not enter in this format XXXX000
Assuming that X means A-Z and a-z and 0 means 0-9 in your pattern, you can use this pattern to valid the code:
[A-Za-z]{4}\d{3}
For more info on regexes, see here.
Use it like this:
if (codeine.matches("[A-Za-z]{4}\\d{3}")) {
// valid
} else {
// invalid
}
Related
import java.util.Scanner;
public class VerifySerialBayneHarris {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String text;
String cha;
System.out.println("Enter a Serial number: ");
text=input.nextLine();
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{
System.out.println("Serial number "+text+" verification \nValid");
System.out.println("Enter a wildchar character: ");
cha=input.nextLine();
text= text.replaceAll("[A-Za-z0-9]", cha);
}
if(text.matches("[^A-Za-z0-9-]+"));
System.out.println("Only uppercase , lowercase letters, dashes and numbers are allowed.It should have exactly 2 non-consecutive dashes in the middle. ");
}
}
This is what I have so far, but I keep getting both of the expressions running instead of one or the other. There must be something I'm missing. Thanks in advance.
Here is my guidelines:
prompts the user to enter a serial number according to the following rules:
Only uppercase and, lowercase letters, dashes and numbers are allowed.
It should have exactly 2 non-consecutive dashes in the middle.
Your program should verify that the serial number is valid and if so, prompt the user to enter a wildcard character. It should then display the concealed serial number by masking all of its characters except the dashes using the wild char character
[What code is supposed to look like]
[1]: https://i.stack.imgur.com/xoGke.jpg
Get rid of the semi-colon here...
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{ << HERE
...and...
if(text.matches("[^A-Za-z0-9-]+")); << HERE
Your blocks are always executing because the if statement has an empty block due to this.
If you have minus in character class then it should be first:
[A-Za-z0-9-] shall be [-A-Za-z0-9]
But I would not include the - in the groups and write the pattern as: [A-Za-z0-9]+(-[A-Za-z0-9]+){2}
Or with POSIX: \p{Alnum}+(-\p{Alnum}+){2}
If you want to access the 3 segments: (\p{Alnum}+)-(\p{Alnum})-(\p{Alnum})
this is my first time asking a question. If I'm breaking any rules let me know please :)
I want to verify that the user only types in only one character and store in a variable I have already declared initially. As well, loop back the question for user to type in again if they did not do what they are asked for
Here is a what I have done so far
import java.util.Scanner;
public class arraytesting {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int user_Choice;
int rowAndcolumns;
char[][] user_Array;
char user_Char;
do {
System.out.print("Enter your choice (1 to 9): ");
user_Choice = myKeyboard.nextInt();
if (user_Choice < 1 || user_Choice > 9)
System.out.println("Illegal choice, please try again.");
} while (user_Choice < 1 || user_Choice > 9);
switch (user_Choice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (rowAndcolumns < 1 || rowAndcolumns > 9)
System.out.println("Illegal choice, please try again.");
} while (rowAndcolumns < 4 || rowAndcolumns > 20);
do {
System.out.print("Which character do you want to fill your square with? (only one character)");
user_Char = myKeyboard.next().charAt(0);
if () // error message for user if they did not type correctly, Idk what to put in the
System.out.println("Illegal choice, please try again.");// boolean for it to compare
System.out.print(user_Char);
} while (); // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
}
I know I can put both of them in one do-while loop, but I want to focus on getting the boolean to check for user input.
edit: I would only like the user to enter only one single character
ex. '#' or 'a'
whereas "##" or "i am typing something that is not one character" is wrong
inside the spaces of if and while are how I want it to be verified
There is no need to do any check for "only 1 character entered". That makes no sense. You can't predict the future, so you cannot know if a user will enter more characters after 1 character has been entered. You will either just take the first character entered and work with it and ignore any potential additional characters - or you have to wait for more than 1 character, essentially breaking the program for users who do the right thing (enter only one character), just to be able to give them an error message when they finally do the wrong thing (enter another character).
That being said, this code:
user_Char = myKeyboard.next().charAt(0);
will actually wait for several characters to be entered until some kind of delimiter (per default some whitespace character, e.g. newline) is entered. That's exactly what you do not want.
You want to get one character from input, and one only. You don't have to care about more characters being entered after that:
user_Char = myKeyboard.next(".").charAt(0);
This tells myKeyboard to return the next String that matches the regex ".", which is any character, and only 1 character.
If you want to validate the entered character, e.g. only alphanumeric characters allowed, you can update your if and while to something like this:
if (!Pattern.matches("[a-zA-Z0-9]", new String(user_Char)))
or even better, use the String returned by myKeyboard.next("."):
String user_String = myKeyboard.next(".");
user_Char = user_String.charAt(0);
if (!Pattern.matches("[a-zA-Z0-9]", user_String))
or you could directly tell myKeyboard to only allow valid characters and skip the entire do/if/while error handling:
user_Char = myKeyboard.next("[a-zA-Z0-9]").charAt(0);
Edit
One thing your code doesn't handle right now is invalid inputs, e.g. letters when you call nextInt. This will actually throw a java.util.InputMismatchException, and you might want to wrap your nextInt() and next(...) calls in try-catch blocks to handle these exceptions.
Please check the code below, based on the discussion with Max, I used the .length() method to check the lenght of the string that the user typed.
You can check the type of the character to avoid the runtime exception in the first if statement using some methods in Character class that you use to check if the input is digit/letter or not ?
Character.isDigit(char)
Character.isLetter(char)
Character.isLetterOrDigit(char)
I also changed some variable names, Java is following the camel case style and class name has to be capitalized. I also refactored some code to check the range of the numbers to git rid of repeating same code on and on, check the method betweenExclusive
package stackoverflow.q2;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
int userChoice;
int rowAndcolumns;
char[][] user_Array;
char userChar;
do {
System.out.print("Enter your choice (1 to 9): ");
userChoice = myKeyboard.nextInt();
if ( !betweenExclusive(userChoice, 1,9) )
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(userChoice, 1,9));
switch (userChoice) {
case 1:
do {
System.out.print("\nHow many rows and columns (min 4 & max 20)? ");
rowAndcolumns = myKeyboard.nextInt();
if (!betweenExclusive(rowAndcolumns ,1 , 9))
System.out.println("Illegal choice, please try again.");
} while (!betweenExclusive(rowAndcolumns ,4 , 20));
String input;
while (true){
System.out.print("Which character do you want to fill your square with? (only one character)");
input = myKeyboard.next();
// error message for user if they did not type correctly, Idk what to put in the
// boolean for it to compare
if ( input.length()>1){
System.out.print("Illegal character, try again please !!! ");
}else{
userChar = input.charAt(0);
System.out.print(userChar);
break;
}
} // using do-while loop to loop back question, if they don't type in correctly, i
// would only like for user to type in only one character
break;
}
}
public static boolean betweenExclusive(int x, int min, int max)
{
return x>=min && x<=max;
}
}
I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}
I am attempting to make it so this program runs again if the user enters 'y'. What happens when the user does this is the program runs again, but not correctly. This is what I have so far. I know a do while loop will be best for this. Is it an error in how the variables are initialized?
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
String runAgain = "";
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
do {
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t" + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toLowerCase()); //lowercase version of the password equals the password,
hasLowercase = !password.equals(password.toUpperCase()); //only if it does not contain uppercase letters.
hasDigit = password.matches(".*[0-9].*");//checks for digits
hasSpecial = !password.matches("[A-Za-z0-9]*"); //for anything not a letter in the ABC's
//prints the verdict
System.out.print("Verdict: ");
if(hasLength)
{
System.out.println("\t\tInvalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("\t\t\tInvalid, Must have an uppercase character");
}
if(!hasLowercase)
{
System.out.println("\t\t\tInvalid, Must have a lowercase character");
}
if(!hasDigit)
{
System.out.println("\t\t\tInvalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("\t\t\tInvalid, Must have a special character");
}
System.out.print("Would you like to make another password? (Y/N) ");
runAgain = scan.next();
System.out.println("\n");
} while (runAgain.equalsIgnoreCase("Y"));
which gives this output when yes is entered to run again. It skips the prompt entirely.
Would you like to make another password? (Y/N) y
A password must be at least 8 character long
And must contain:
-At least 1 number
-At least 1 uppercase letter
-At least 1 special character (!##$%^&*()_+)
Please enter your new password:
Entered Password:
Verdict: Invalid, Must have at least 8 characters
Invalid, Must have an uppercase Character
Invalid, Must have a lowercase character
Invalid, Must have a number
Invalid, Must have a special character
Would you like to make another password? (Y/N)
You would need to read the complete line form console at runAgain = scan.next();. Just single token is being read to runAgain and the console is left with \r or Return character which will be read as next password where you do scan.nextLine(). You may change the statement to runAgain = scan.nextLine().trim();.
System.out.print("Would you like to make another password? (Y/N) ");
// runAgain = scan.next();
runAgain = scan.nextLine();
System.out.println("\n");
I'm running a java program I created that stores data inputted by user. Specifically 4 array lists which are songName, songArtist, songYear & songAlbum.
I have a user input for "songYear" and I only want the program to accept a maximum of 4 digits in length and give an error otherwise, how can this be achieved?
here's the code I have for my add entry method:
public void addEntry(){
String newName = ui.getString("Enter the name of the track");
songName.add(newName);
String newArtist = ui.getString("Who performs this track");
songArtist.add(newArtist);
String newAlbum = ui.getString("What album is this track from");
songAlbum.add(newAlbum);
System.out.print("What year was the track released? ");
int newYear=input.nextInt(4);
songYear.add(newYear);
System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
System.out.println("\n" + "Press 2 to view your library." + "\n");
}
You can use regex like: ^.{4}$
Means only if user typed 4 digits - return true, otherwise return false
To be sure that user used 4 numbers YYYY use something like:
^(?=[1-9]+)\d{4}$
Makes sure the year is 1 or 2 followed by three numbers; valid ranges in this case would be 1000-2999
^(?=[1-2][0-9]+)\d{4}$
Finally your code should be like:
if(inputUserStr.matches("^(?=[1-2][0-9]+)\d{4}$")){
// do some stuff
}
else{
// print error about valid input form [YYYY]
}
Depends entirely on the language but some approaches are:
check the string input using a len function; or
convert it to an integer and ensure it's less than 10,000; or
a regular expression like ^\d{1,4}.
No doubt there'll be other validation checks such as ensuring string input is all-numeric, and you're not trying to input a song that was written twenty years in the future, but they're added checks you should consider.
1) Accept the user's input and using the substring method, save only the first four characters (Specify to user that first 4 characters are considered).
2) You can ask the user to reenter the value if it is not 4 characters:
Scanner sc = new Scanner(System.in);
String a = sc.next();
if (a.matches("...."))
{
System.out.print(a);
}
else
{
System.out.print("Input again:" );
a = sc.next();
}
I've written a sample regex for 4 characters. But you can always change it.