Finding if a specific character exists at a specific index - java

so I'm trying to figure out how to create a condition for my decision structure. I'm making a program that converts military time to conventional time. When times are entered, they must be in a XX:XX format, where X equals a digit. I'm wondering, how can I make a validation that checks to make sure that ":" always exists as a colon and is in the same spot?

myString.charAt(5) == ':'
Just change 5 to whatever you need, and check string length before you do this, so you don't ask for something past the end of a short string.

You could search the string with indexOf(), which returns the index at which the character is found. This will check if a colon is in the string and if it's in the right position.
if("10:00".indexOf(':') == 2)
// do something
It will return -1 if the value is not found. Check out the java documentation for more information.

Here is the answer for it
Suppose you had string that contains XX:XX
yourString="XX:XX"
yourString.contains(":") - return true - if exists
":" takes the 3rd position. So it will be 2(0,1,2)
yourString.charAt(2) == ':'
Together , it will be
if(yourString.contains(":") && yourString.charAt(2) == ':'){
//your logic here
}else{
something here
}

Here is one approach to that,
String[] test = new String[] { "00:00", "NN:NN", "12,13", "12:13" };
for (String fmt : test) {
boolean isValid = true;
for (int i = 0; i < fmt.length(); i++) {
char c = fmt.charAt(i);
if (i == 2) {
if (c != ':') { // here is the colon check.
isValid = false;
break;
}
} else {
// This checks for digits!
if (!Character.isDigit(c)) {
isValid = false;
break;
}
}
}
System.out.println(fmt + " is " + isValid);
}
Output is
00:00 is true
NN:NN is false
12,13 is false
12:13 is true

#WillBro posted a good answer but I give you another option:
myString.indexOf(":") == 5
With indexOf you can also look for full String inside a String.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
But for string format validations I suggest you to use Regular Expresions.
Here's a full example that does what you want to do:
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

Related

finding number of words present in the string in java using recursion

A class words defines a recursive function to perform string related operations. The class details
are given below:
Class name : words
Data members/instance variables
text : to store string.
w : integer variable to store total words.
Member functions/methods
words( ) : constructor to store blank to string and 0 to integer data.
void Accept( ) : to read a sentence in text. Note that the sentence may contain more
than one blank space between words.
int FindWords(int) : to count total number of words present in text using Recursive
Technique and store in ‘w’ and return.
void Result( ) : to display the original string. Print total number of words stored in
‘w’ by invoking the recursive function.
I tried this code
public static int CountWords(String str) {
int c = 0;
int i = str.indexOf(" ");
if (str.isEmpty()) {
return 0;
}else
if (i == str.indexOf(" ")) {
return c++;
}
//str.substring(0,str.indexOf(" ")-1);
c++;
return c + CountWords(str.substring(i + 1));
}
but i need to return an integer value and i am confused with that..
In your code, the last return statement is inaccessible. Reason: you have put an if-else block and have put return in both the cases. So the function actually gets returned from the if-else block itself (within else, the condition of if is always true since you assigned the very value i.e. str.indexOf(" ")).
I have written down the code according to the question you gave above...
public int findWords(int i){
if(i > text.lastIndexOf(" "))
return 1;
i = text.substring(i).indexOf(" ") + i;
if(i < 0)
return 1;
if(text.substring(i).equals(null))
return 0;
return( findWords(i+1) + 1);
}
Hope you find it well working.
Your function already is returning a integer, it just happens to always be 0.
This is due to
else if (i == str.indexOf(" ")) {
return c++;
}
Always being true and c++ only updating after the return statement was passed.
This happens because you already set i to be the indexOf(" ") and due to the implementation of incrementation using int++. Also, keep in mind hat you need to increase the number of words by 2 here, since you're ending the function between two words.
Therefore, use this instead:
else if (i == str.lastIndexOf(" ")) {
return c+2;
}
You should see that now the function is returning the correct amount of words.

Join path that overlaps

In java, I have a string that looks like :
"c:\abc\def\ghi"
and another that is
"def\ghi\jkl.txt"
How can I do the intersection of both to have
"c:\abc\def\ghi\jkl.txt"
edit :
The rules are :
replace the maximum of the end of the first string with the maximum of the beginning of the second string.
For example with
b\a\n\a\n\a and a\n\a\n\a\s the result should be b\a\n\a\n\a\s
with "c:\abc\def\ghi" joined to "def\gji\jkl.txt", we have "c:\abc\def\ghi\def\gji\jkl.txt"
I would simply look at the first string and check if it ends with the largest possible beginning of the second string. To be a little bit faster I check on every existing backslash:
public static String join(String begin, String end) {
for (int i = end.lastIndexOf("\\"); i >= 0; i = end.lastIndexOf("\\", i - 1)) {
if (begin.endsWith(end.substring(0, i)) && begin.charAt(begin.length() - (i+1)) == '\\') {
return begin + end.substring(i);
}
}
return "strings dont contain same folder sequence";
}

Can't get java to match regex with matches()

I have a problem where I'm trying to get a parameter to match the format 'Uddd' where 'U' MUST be the letter U and 'ddd' can be any 3 digits from 0-9.
My current code:
//borrow method
public boolean borrow(String borrowerID)
{
//if the borrower ID matches the format 'Uddd'
if (borrowerID.matches("U([0-9]{3})"))
{
//if the status is available
if (status == 'A')
{
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
}
//is not available
else
{
return false;
}
}
//does not match format
else
{
return false;
}
}
For some reason it's not validating properly. When I tried inputting '1' as the parameter, it still returned true.
Is there something I'm missing?
It should not be possible for that method to return true if the input is "1". I can only suggest you ensure you are passing in "1" and that the method is the one being called.
That can be done with a simple debug statement at the top, something like:
System.out.println ("Calling correct function with [" + borrowerId + "]");
at the start of the function.
I'd also suggest a bit of clean-up to make the function easier to code and read, along the lines of:
// borrow method
public boolean borrow(String borrowerID)
{
// Temp debug statement.
// System.out.println ("borrow [" + borrowerId + "]");
// "Not available" or "invalid borrower" means reject request.
if (status != 'A')
return false;
if (! borrowerID.matches("U([0-9]{3})"))
return false;
// Okay to borrow.
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
}
This is a lot cleaner than all those return-else-do-something constructs, and it follows a "fail fast" paradigm.
Some people tend to dislike multiple return points but that's usually because they don't understand why they're considered bad (spaghetti code). With a short function like this, it doesn't pose a problem.
I get good results with your regex : "1" -> false, "UU123" -> false, "U1234" -> false, "U132" -> true.
but you can use \d instead of [0-9] :
borrowerID.matches("U(\\d{3})")
actually that's not possible.when input 1 it won't return true but it return false.may be your status is equal 'A' that should be reason to return true
String borrowerID="1";
boolean matches = borrowerID.matches("U([0-9]{3})");
System.out.println(matches);
output>>
false
if you only want to find is regex match or not then use this .or put a sout and check does status value.definitely it should be A
if (borrowerID.matches("U([0-9]{3})")) {
return true;
} else {
return false;
}
There is no issues with your regex
System.out.println("U888".matches("U([0-9]{3})"));
Output true
System.out.println("1".matches("U([0-9]{3})"));
Output false
Try debug your code, with few breakpoint inside your borrow function
You can also optimize your like
if (borrowerID.matches("U([0-9]{3})") && (status == 'A')) {
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
} else {
return false;
}
I don't understand onething, you are checking the status againist 'A' and inside assignin '0', does it make sense?(Anyway it's upto you)

Java - validating a subject Code

I have a subject code e.g: ABC123 that is a string
I need to ensure that it is of length 6, the first 3 characters are letters and the last 3 are numbers.
I would like to try and do it all in an if statement? I can work the length but cannot figure out the numeric and letter part of things. e.g:
public void isValidCode(String subjectCode2){
str = subjectCode2;
if (str.length() == 6 && """"NEED TO TEST OTHERS HERE??""" ) {
System.out.println("The code is valid");
}
else {
System.out.println("The code is not valid");
}
You can always use Regular Expressions, and the matches() method of the String class.
if (str.matches("[a-zA-Z]{3}[0-9]{3}")) {
// Validation succeeded
}
else {
// Validation failed
}
To test that the first three letters are letters, you could use a loop. Similarly, use a loop for testing that the last three digits are numbers. You might find the functions in the Character class helpful.
I would change the method signature so that it is not a void method but rather declared to return a boolean. Then you could have several if statements that if false returns false. At the bottom, return true if it passes all tests.
public boolean isValidCode(String code) {
if (code.length() != 6) {
return false;
}
// here check if first 3 chars are letters
// here check if last 3 chars are numbers
return true;
}
Then the calling code can do a println if desired.
String test = "ABC123";
if (isValidCode(test)) {
System.out.println("The code is valid");
} else {
System.out.println("The code is not valid");
}
If by "letter", you mean to include letters in alphabets other than English, you'll need this.
if (str.matches("\\p{L}{3}\\d{3}")) {
Here, \p{L} matches any character that Unicode considers to be a letter, in any language.

Java - See if a string contains any characters in it

The problem i'm having is when i check to see if the string contains any characters it only looks at the first character not the whole string. For instance I would like to be able to input "123abc" and the characters are recognized so it fails. I also need the string to be 11 characters long and since my program only works with 1 character it cannot go any further.
Here is my code so far:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
For instance why if i take away the checking to see the phoneNumber.length() it still only registers 1 character so if i enter "12345" it still fails. I can only enter "1" for the program to continue.
If someone could explain how this works to me that would be great
Your regex and if condition is wrong. Use it like this:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
This will only allow phoneNumber[a] to be a 11 character long comprising only digits 0-9
The + should be outside the set, or you could specifically try to match 11 digits like this: ^[0-9]{11}$ (the ^ and $ anchor the match to the start and end of the string).
You need to put the "+" after the "]" in your regex. So, you would change it to:
phoneNumber[a].matches("[0-9]+")
Why not try using a for loop to go through each character?
Like:
public static int phoneNumber(int a)
{
while (invalidinput)
{
int x = 0;
for(int i = 0; i < phoneNumber[a].length(); i++)
{
char c = phoneNumber[a].charAt(i);
if(c.matches("[0-9+]")){
x++;
}
}
if (x == phoneNumber[a].length){
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
Are the legal characters in your phone numbers 0..9 and +? If so, then you should use the regular expression [0-9+]*, which matches zero or more legal characters. (If not, you probably meant [0-9]+.) Also, you can use [0-9+]{11} instead of your explicit check for a length of 11.
The reason that your current code fails, is that String#matches() does not check whether the regular expression matches part of the string, but whether it matches all of the string. You can see this in the JavaDoc, which points you to Matcher#matches(), which "Attempts to match the entire region against the pattern."

Categories

Resources