Java check String input - java

I am trying to check an input String:
- length
- type
- special char at the end
The input is a identity card like this 24659213Q.
So what I got for now is:
public void datosUsuario() {
System.out.print("Write ID: ");
input = scanner.nextLine();
}
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9){
status = true;
System.out.println("Length: OK!");
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}
}
So I am checking the entire String for having 8+1 length and now I am having problems checking if it has 8 digits and a char at the end of the input.
Any ideas would be apreciated! Thank you!

I'd use a regular expression:
String input = scanner.nextLine();
input.matches("/^[0-9]{8}[A-Za-z]$/);
See String.matches and regular expression documentation.

A simple method would be:
//ID check
public void comprobacion() {
System.out.println("Checking ID length...");
if (input.length() == 9) {
if (Character.isAlphabetic(input.charAt(8)) {
status = true;
System.out.println("OK!");
} else {
status = false;
System.out.println("Length: OK, but last character must be alphabetic");
}
} else {
System.out.println("Length not OK! Try again!\n");
status = false;
}

You can use reg ex,
public static void comprobacion(String input) {
status = false;
if(input.matches("\\d{8}\\w{1}"))
{
status = true;
}
}
Here, \d{8} = eight digits
\w{1} = one alphabetical character

You could use "Character.isDigit()" to determine if a character is a digit or not. In other words, you could create a for loop to interate through each character, checking whether it is a digit or not. Here's an example:
String input = "24659213Q";
for(int c = 0; c < input.length()-1; c++){
//Checks all but the last character
if( !Character.isDigit( input.charAt(c) ) ){
System.out.println("The String does not start with 8 digits");
}
}
if( Character.isDigit( input.charAt(8) ) ){
//Checks only last character
System.out.println("The String does not end with a char");
}

The method of regular expression can also be followed as mentioned above. There is one more way to do it.
1)Split the string into two -one with 8 characters and the other with last one character.
2)Parse the first String
Integer.parseInt(subStringOfFirst8Char) in a try catch block catching NUmberFormatException.
If you don't catch the exception it is alright else it is wrong.

Related

How to validate string if the first 3 positions are letters

I'm trying to validate a string entered by a user. The user must enter a string with 7 characters; the string first 3 characters must be letters and the last 4 must be numbers.
I wrote this piece of code( as a method ) but for some reason it accepts the first character as a number ( which it's suppose to be a letter ) and the rest are numbers. For example :
Please enter word : **1gy2345**
This will enter the loop, as wanted, and move on into the next method in the main.
If the user enters a word that its length is bigger than 7 it will ask him to enter a valid word.
For example :
Please enter word : **bob12345**
The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
Here is my code:
public static final String solicitationMessage = " Please enter word ";
public static final String errorMessage = " The word entered is invalid. Please enter a word beginning with 3 letters and ending with 4 numbers ( The word must be 7 characters long ).
public static final int lengthOfString = 7;
public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {
System.out.print(solicitationMessage);
String word = keyboard.nextLine();
while (!( word.length() == lengthOfString )) {
if (((word.charAt(0) <= 'a' || word.charAt(0) >= 'z') || (word.charAt(1) <= 'a' || word.charAt(1) >= 'z')
|| (word.charAt(2) <= 'a' || word.charAt(2) >= 'z'))) {
System.out.print(errorMessage);
System.out.print(solicitationMessage);
word = keyboard.nextLine();
}
}
return word;
}
However, if I enter a string higher than the 7 limit character it will ask me again the enter a valid string like it's suppose to do.
The use of regex is not permitted.
Any help ?
This is easy task for regex
[a-zA-Z]{3}[0-9]{4}
Some test cases: http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyEwsSBlJlY2lwZRiAgICi0ZuYCgw/index.html
So it can be something like
Pattern pattern=Pattern.compile("[a-zA-Z]{3}[0-9]{4}");
String line;
while(true){
line= keyboard.nextLine();
if(pattern.matcher(line).matches()){
break;
}
}
Since this is an assignment I will only give you the pseudo code. You try to figure out how to implement it :p
boolean function validateString(inputString):
check if inputStrings length is exactly 7:
if not then return false;
loop through inputString:
if the current index is less than 3 and current character is within 'a' - 'z' or within 'A' - 'Z' // check if current character is a letter
return false;
else if current index is greater than 2 and current character is not within '0' - '9' // check if current character is not a digit
return false;
end loop
return true
end function
Then just call that function in your main method and print necessary error messages.
Try this. Use the Character class to test the characters.
if (!(Character.isLetter(word.charAt(0)) &&
Character.isLetter(word.charAt(1)) &&
Character.isLetter(word.charAt(2)))) {
System.out.print(errorMessage);
System.out.print(solicitationMessage);
word = keyboard.nextLine();
}
May be this would help.
public static String validateString(String solicitationMessage, String errorMessage, int lengthOfString) {
System.out.print(solicitationMessage);
String word = "";
boolean flag = false;
while (true) {
Scanner sc = new Scanner(System.in);
word = sc.nextLine();
if(word.length() == lengthOfString){
for(int i=0;i<word.length();i++){
int ascii = (int)word.charAt(i);
if(i<3 && (ascii > 64 && ascii < 123)){
flag = true;
}else if(i>2 && (ascii > 47 && ascii < 58)){
flag = true;
}else{
flag = false;
System.out.println(errorMessage);
break;
}
}
if(flag){
break;
}
}else{
System.out.println(errorMessage);
}
}
return word;
}

java validate String containing numbers and search to make sure there are no characters

I want to validate a user input phone number, the first thing I need to do is check to make sure that the length of the input string is 10 which isn't an issue as you'll see in my code.
Now is where the problem comes in, I also need to check to make sure no characters have been entered in as well, any ideas on how to do this with out the use of Arrays. I'd like to use Character.isLetter(); but no matter how I implement it it's not coming out right.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isNumber = false;
String phoneNum = "";
Scanner input = new Scanner(System.in);
while(!isNumber)
{
System.out.print("\nEnter your 10 digit phone number (ex: 2123345657): ");
phoneNum = input.nextLine();
/* Yes I could use nextInt(); etc.. but that would defeat the
purpose of this exercise */
if(phoneNum.length() != 10)
{
System.out.println("\n\nBad input");
}
else
isNumber = true;
}
System.out.println("\n\nPhone number is: " + phoneNum);
}
}
I was looking for some thing like this.
while(!isRight)
{
System.out.print("\n input number: ");
phoneNum = input.nextLine();
while(i < phoneNum.length())
{
if(phoneNum.length() != 10)
{
System.out.println("not enough numbers");
}
else if (Character.isLetter(phoneNum.charAt(i)) == true)
{
System.out.println("Sorry you can't use any thing but numbers");
}
else
isRight = true;
i++;
}
}
You can do it without a regex:
boolean validate(String str) {
if (str.length() != 10) {
return false;
}
for (int i = 0; i < str.length(); ++i) {
if (!Character.isDigit(str.charAt(i)) {
return false;
}
}
return true;
}
use a regex of
"^[0-9]{10}"
or if it has to start with non-zero
"^[1-9][0-9]{9}"
if(!phoneNum.matches("^[0-9]{10}")) {
// ok
}
If you want to use isLetter
then try
boolean allNum = true;
for (char ch : phoneNum.toCharArray ()) {
if (Character.isLetter (ch)) {
allNum = false;
break;
}
}
You can use String regex matching to check whether string is a numeric or not:
boolean numeric = phoneNum.matches("\\d+");
As an alternative solution, if you have apache commons library imported in the project, you can use isNumeric method of StringUtils class, e.g.:
StringUtils.isNumeric(phoneNum);
You can use this:
/* Check is numeric */
StringUtils.isNumeric(yourNumber);
or REGEX to avoid all characters diferente of numbers.
`{\\d+}`
I wanted to post the solution I came up with, for a few reasons but mainly so that if so some one is having issues and they're intentionally avoiding Arrays, regex etc.. they can have a good example!
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isNumber = false;
String phoneNum = "";
Scanner input = new Scanner(System.in);
while(!isNumber)
{
isNumber = true;
System.out.print("\nEnter your 10 digit phone number (ex: 4142317534): ");
phoneNum = input.nextLine();
for(int i = 0; i < phoneNum.length(); i++)
{
if(!Character.isDigit(phoneNum.charAt(i)))
{
isNumber = false;
}
}
if(phoneNum.length() != 10)
{
isNumber = false;
}
if(isNumber == false)
{
System.out.println("\n\nInvalid format - please reenter");
}
}
System.out.println("\n\nPhone Number: " + phoneNum);
}
}
Yes it's a lot of code yes it can be condensed, but it's more important to learn and understand how things work and why they work they way they do before you attempt to be efficient, efficiency comes with learning and working the more you do the better you get and the more waste you cut out!

Java- index out of range: 0

I am desperately trying to figure out a way of stopping "String index out of range: 0" errors... It happens whenever I don't enter anything and then continue execution:
static String getRef(Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
String ref= "";
boolean valid = false;
int errors = 0;
boolean problem = false;
while(valid==false)
{
System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
ref = keyboard.nextLine();
for (int i=0; i<6; i++)
{
if (ref.charAt(i)=='\0')
{
problem = true;
}
}
if(problem == true)
{
System.out.println("The reference must consist of 6 Characters");
}
else
{
if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
{
System.out.println("The first 2 characters must be letters");
errors = errors + 1;
}
if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
{
System.out.println("The 3rd,4th and 5th characters must be numbers");
errors = errors + 1;
}
if ((!ref.toUpperCase().endsWith("B"))&&(!ref.toUpperCase().endsWith("N")))
{
System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
errors = errors + 1;
}
if (errors==0)
{
valid=true;
}
}
}
return ref;
}
What I want is to be able to output an error message if the string does not contain a character at a certain index e.g. ref.charAt(0).
This will help (example):
if(ref.charAt(aNumber)==null) {
// display error message
}
Your problem is here:
ref.charAt(i)=='\0'
What happens if ref is a zero length string? In that case, trying to access the character at index 0 (where the first character would normally be) will give you your index out of range: 0 error. Make sure you test the string length first:
if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0') { .. }
Adding a length() check
ref is empty (that is "") when you don't enter anything. So you can't get the character at 0 (or 1, 2, 3 ...). You can add an if check on the length, something like
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
Regular Expression
It might be simpler to compile a (reusable) Pattern with a regular expression to validate your reference criteria (2 letters, followed by 3 digits, followed b or n). Something like,
String ref; // <-- get input
Pattern p = Pattern.compile("([a-zA-Z]{2})(\\d{3})([B|N|b|n])");
Matcher m = p.matcher(ref);
if (m.matches()) { // <-- valid = m.matches();
System.out.println("ref is valid");
} else {
System.out.println("ref is not valid");
}

How do I tell user that they've previously entered a letter with indexOf? JAVA

When the user enters a letter it gets added to newString everytime. How do I return an error message if the user inputs the same letter more than once?
So for example user inputs: a, b, then c
then newString = "abc"
I just can't work out how to check whether the user has already entered a letter.
If they enter a again for example it should return an error message.
Here's what I have so far:
if (newString.indexOf(input) != -1 ) {
System.out.println( "Invalid" );
}
I imagined it would work because it is looking through newString for input and if it isn't there it will return -1.
If I am understanding your question correctly I believe you can use the String contains method to check for a letter. It would be something like this:
if(newString.contains(letter))
Use contains
String s = "helo";
if (s.contains(input)){
// reject
}
or
if (!s.contains(input)){ // if string does not contain input
s += input; // concatenate to string
}
Try this
if(newString.indexOf(letter) != -1){
//Invalid
}
Try this
public static void main(String[] args) throws IOException {
String newString = "";
System.out.print("Enter letter: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toUpperCase();
while(true){
if (newString.contains(input))
{ System.out.println( "Invalid" );}
else
{
newString = newString+ input;
}
input = br.readLine().toUpperCase();
}
}
Each time a user enters a character, check that character against existing characters in the String. So each time a user enters a character, do something like this:
for (int i = 0; i < newString.length(); i++) {
if (newString.charAt(i) == input) {
System.out.println("Invalid");
}
else {
System.out.println("Valid");
}
}

help with making a password checker in java

I am trying to make a program in Java that checks for three specific inputs. It has to have pass these tests:
At least 7 characters.
Contain both upper and lower case alphabetic characters.
Contain at least 1 digit.
So far I have been able to make it check if there is 7 characters, but I am having trouble with the last two. What should I put in my loop as an if statement to check for digits and make it upper and lower case. Any help would be greatly appreciated.
Here is what I have so far.
import java.awt.*;
import java.io.*;
import java.util.StringTokenizer;
public class passCheck
{
private static String getStrSys ()
{
String myInput = null; //Store the String that is read in from the command line
BufferedReader mySystem; //Buffer to store the input
mySystem = new BufferedReader (new InputStreamReader (System.in)); //creates a connection to system input
try
{
myInput = mySystem.readLine (); //reads in data from the console
myInput = myInput.trim ();
}
catch (IOException e) //check
{
System.out.println ("IOException: " + e);
return "";
}
return myInput; //return the integer to the main program
}
//****************************************
//main instructions go here
//****************************************
static public void main (String[] args)
{
String pass; //the words the user inputs
String temp = ""; //holds temp info
int stringLength; //length of string
boolean goodPass = false;
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys (); //get words from system
temp = pass.toLowerCase ();
stringLength = pass.length (); //find length of eveyrthing
while (goodPass == false)
{
if (stringLength < 7)
{
System.out.println ("Your password must consist of at least 7 characters");
System.out.print ("Please enter a password: "); //ask for words
pass = getStrSys ();
stringLength = pass.length ();
goodPass = false;
}
else if (/* something to check for digits */)
{
}
}
Sure you can come up with a convoluted—almost unreadable—regex for doing this but I wouldn't suggest it. Apart from the readability aspect, if the password fails it doesn't tell you why. This solves both of these problems:
while (true) {
pass = getStrSys();
if (pass.length() < 7) {
System.out.println("must be at least 7 characters long");
} else {
boolean upper = false;
boolean lower = false;
boolean number = false;
for (char c : pass.toCharArray()) {
if (Character.isUpperCase(c)) {
upper = true;
} else if (Character.isLowerCase(c)) {
lower = true;
} else if (Character.isDigit(c)) {
number = true;
}
}
if (!upper) {
System.out.println("must contain at least one uppercase character");
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
} else if (!number) {
System.out.println("must contain at least one number");
} else {
break;
}
}
}
A regular expression is more appropriate for what you are trying to accomplish. For instance, using lookahead assertions, you'd use something like this:
Pattern p = Pattern.compile("^.*(?=.{7,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$");
String pass = getStrSys();
Matcher m = p.matcher(pass);
if (m.matches()) {
System.out.println("Valid password.");
} else {
System.out.println("Invalid password.");
}
Don't use StringTokenizer. Use String.split.
Use the functions in the Character class to check for upper case, lower case, or numeric.
Since you've forced lower case, you can't check. You need to get rid of that.
In your situation. There should be two condition true for validation. I think following will be the best approach to achieve it.
private static final char[] SPECIAL = "$!+\-#?_%&/".toCharArray();
private static final char[] NUMBER = "0123456789".toCharArray();
public static boolean checkValidation(String password)
{
int points = 0;
String lowerPass = password.toLowerCase();
String upperPass = password.toUpperCase();
if(!password.equals(lowerPass) && !password.equals(upperPass))
{
// if contains upper or lower letter
points++;
}
if(contains(password, SPECIAL))
{
// if it contains special character
points++;
}
if(contains(password, NUMBER))
{
// if it contains Number
points++;
}
return points >= 2;
}
public static boolean contains(String pwd, char[] value)
{
int i = 0;
boolean success = false;
while(i < value.length && !success)
{
if(pwd.indexOf(""+value[i]) != -1)
{
success = true;
}
i++;
}
return success;
}

Categories