How to validate string if the first 3 positions are letters - java

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;
}

Related

How to check two indices of a string to see if the characters match

I am trying to check two different indices to see if they match. In my case I am checking indices 3 and 4. I have no problem determining if they match or not, but if my string is too short and does not have a character in at index 3 or 4 my program throws a fit.
Here is a copy of my code. Can anyone tell me what I am doing wrong?
/**
* Checks the characters in a String at indices 3 and 4 to see if those characters match
* #param input String to check
* #return "MATCH" if String's indices 3 and 4 have the same letter, "NO MATCH" if String's
* indices 3 and 4 do not have the same letter, "N/A" if the String is too short to have a letter at index 3 or index 4
*/
private static String method4(String input) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your word? ");
input = scan.nextLine();
int len = input.length();
if (len < 4) {
System.out.println("N/A");
}
else{
char char1 = input.charAt(3);
char char2 = input.charAt(4);
if ((char1) == (char2)) {
System.out.println("MATCH");
}}
else
System.out.println("NO MATCH");
The method your using charAt is zero based like an array.
if (len < 4) {
System.out.println("N/A");
}
Only ensures that the string has at least 4 characters, the fourth having index 3.
"abcd".charAt(3) == 'd'
So when the the string has exactly 4 characters input.charAt(4) will throw an exception.
try (Scanner scan = new Scanner(System.in)) {
System.out.println("What is your word? ");
String str = scan.nextLine();
int len = str.length();
if (len < 5)
System.out.println("N/A");
else if (str.charAt(3) == str.charAt(4))
System.out.println("MATCH");
else
System.out.println("NO MATCH");
}
As mentiont in other post:
String str = "abcd";
str.legnth == 4
str.charAt(3) == 'd' // zero-based

How can I modify my code to only accept a certain data type?

What can I do to modify this, is there any java function for that?
What needs to be done so that it only accepts characters and returns an error message for other data types?
import java.util.*;
public class problem5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter from the alphabet: ");
char letter = in.next(".").charAt(0);
char vowels[] = {'A','E','I','O','U','a','e','i','o','u'};
int vowelcount = 0;
for (int i = 0; i < 10; i++)
{
if (vowels[i] == letter)
{
vowelcount++;
}
}
if (vowelcount > 0)
{
System.out.println("You entered a vowel.");
}
else
{
System.out.println("You entered a consonant.");
}
}
}
I need to reject input that has more than 1 char – Nico Dela Cruz
You just need to check the length of your input
String input = in.next(".");
if(input.length == 1){
char letter = input.charAt(0);
...
}
Add an else if you want to add an error message of some sort.
To check the input to only accept letter, you have Character.isLetter(char) to check every "letter" in UNICODE for you.
If you want to only accept a range of a-z and/or A-Z, you can do it yourself with an if condition or using regex.
Wrap your loop in a statement such as:
if (Character.isLetter(letter)){
and put and else clause at the end for your error
Edit:
OP has changed their question slightly, so you can either:
-Accept only the first character entered:
char letter = in.next().trim().charAt(0);
-Or as AxelH said above, only proceed if user enters one char:
if(input.length == 1){
char letter = input.charAt(0);

Can anyone help me figure out why I'm stuck in a loop? And can I write it simpler?

my goal is to take the first letter of a word and moving it to the end until the first letter is a vowel. this is pig latin
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
String y = word.substring(0,1);
String z = word.substring(1);
char x = Character.toLowerCase(word.charAt(0));
if ((x=='a') || (x=='e') || (x=='i') || (x=='o') || (x=='u')) {
System.out.println(word + "ay ");
}
while ((x!='a') || (x!='e') || (x!='i') || (x!='o') || (x!='u')) {
String s = z+y;
System.out.println(s);
}
Your error is that in your while loop, you never update the value of x. Therefore the program never terminates. In an effort to make your "pig latin" more readable and easier to debug, you should consider breaking your program into methods.
Such as:
public static boolean isVowel(char input){
input = Character.toLowerCase(input);
return ((input=='a') || (input=='e') || (input=='i') || (input=='o') || (input=='u'));
}
So that then you would be able to do:
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
while (!isVowel(word.charAt(0))){ //while the first character isn't a vowel do this:
word = word.substring(1) + word.charAt(0);
}
System.out.println(word);
However beware that if there is no vowel this program will still run into a infinite loop.
Without methods the code would look something like this:
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
char currentChar = Character.toLowerCase(word.charAt(0));
while (!((currentChar=='a') || (currentChar=='e') || (currentChar=='i') || (currentChar=='o') || (currentChar=='u'))){ //while the first character isn't a vowel do this:
word = word.substring(1) + word.charAt(0);
currentChar = Character.toLowerCase(word.charAt(0));
}
System.out.println(word);
Hope this helps :)
You keep doing checks on the variable x, but you are not updating its value in the loop body. Therefore, the condition keeps being verified.
In other words
First iteration: Is x different from a vowel?
If so, build the s string and print it
Second iteration: Is x different from a vowel?
Same as 2... and so on.

Why its gets error when my input string ends with spaces..?

// Count total no of words in String
class Word
{
static int Wordcount(String k)
{
int count=0;
char ch[]=k.toCharArray();
for(int i=0;i<k.length();i++)
{
if(ch[i]==32 && ch[i+1]!=32)
{
count++;
}
}
return(++count);
}
public static void main(String... s)
{
String k="java is a programming lan";
/* if input string is "java is a prog lan " then its gives//Exception
*/
int b=Wordcount(k);
System.out.println("Your input String has "+b +" words");
}
}
// Exception aati h agr string khtm ho ri h space se
if(ch[i]==32 && ch[i+1]!=32)
If ch[i] is the last character in the string, and the code tries to check ch[i+1], then you are outside the string's range, and you get an error.
If you want your condition to match spaces at the end of the string, then you can use
if (ch[i]==32 && (i+1 == ch.length || ch[i+1]!=32))
If you want your condition to match only if there is a non-space character after, then you can use
if (ch[i]==32 && i+1 < ch.length && ch[i+1]!=32)
You are checking the current index and the next index at the same time with this condition:
if(ch[i]==32 && ch[i+1]!=32)
If you are on the last character and it's a space, then ch[i+1]!=32 will be evaluated, causing the exception.
To resolve this, make sure you're not at the end of the array when checking index i+1.
if(ch[i]==32 && i < k.length() - 1 && ch[i+1]!=32)

checking a String for anything other than an integer or character a - z

This is dealing with java to start.
My goal is to take in a Vin number and store it into a string. Make sure it has no more than 9 characters. Also the Vin Number is only supposed to contain numbers and letters a-z or A-Z. If the user inputs an invalid Vin number it should loop back around and prompt for a new Vin Number. My problem is telling whether the string contains anything other than integers or letters. I've seen the Utility.IsAlphaNumeric method but I can't figure out how to implement it or whether it's even a java method. NetBeans gives me errors whenever I try to use it.
private static String checkVin() {
Scanner input = new Scanner(System.in);
String vinNumber = "";
do {
System.out.println("Please enter the vin number of the car");
vinNumber = input.next();
if (vinNumber.length() > 9) {
System.out.println("invalid input for Vin number");
}
for (int i = 0; i < vinNumber.length(); i++) {
char currentCharacter = vinNumber.charAt(i);
if ((currentCharacter < '0' || currentCharacter > '9')
|| !( currentCharacter < 'a' || currentCharacter > 'z')
|| !(currentCharacter > 'A' || currentCharacter > 'Z'));
System.out.println("invalid input for Vin Number");
break;
}
return vinNumber;
} while (true);
}
Utility is not the name of a class from the core libraries.
You can replace the entire check loop with
import java.util.regex.Pattern;
import java.util.regex.Matcher;
private static final Pattern VALID_VIN_NUMBER = Pattern.compile(
"[0-9a-zA-Z]{1,9}");
public static boolean isVin(String s) {
return VALID_VIN_NUMBER.matcher(s).matches();
}
Don't have time for a long answer, but
Pattern p = Pattern.compile("^[A-Za-z0-9]{0,9}$");
boolean matches = p.matcher(s).matches();
This is telling it to look for
string starts (^)
"any number or letter, lowercase or uppercase" ([A-Za-z0-9])
"0 to 9 of them" ({0,9})
string ends ($)
The best mechanism is to use a Regex to ensure it matches a certain pattern. Try:
vin != null && vin.matches([a-zA-Z0-9]{9}))
This will ensure that the vin string is a 9 character string and is only alphanumeric.

Categories