Reputation: 13
Hello im very new to java and im currently taking a introduction to programming class using java. Im having trouble finding the specific position of a character. the entry is suppose to be all numbers and if there is a letter, its suppose to tell what position the letter is located. also i cannot use Loops for this assignment. This is the best result that i have gotten so far but it only works if the entry has an x. how can i make it to show the position of any letter in the alphabet? im sorry if i sound stupid but im very very new to java. thanks in advance.
String alphabet = "x";
if (!isbn.matches("[0-9]+")) {
System.out.println("You need to enter a numeric digit at position " + isbn.indexOf(alphabet));
Upvotes: 0
Views: 191
Reputation: 159165
Flip the regular expression to search for invalid characters:
String isbn = "978-3-16-148410-0";
Matcher m = Pattern.compile("[^0-9]").matcher(isbn);
if (m.find())
System.out.println("You need to enter a numeric digit at position " + m.start());
Output
You need to enter a numeric digit at position 3
Improved print
System.out.printf("You need to enter a numeric digit at position %d%n %s%n%" + (m.start() + 3) + "s%n", m.start(), isbn, "^");
Output
You need to enter a numeric digit at position 3
978-3-16-148410-0
^
Upvotes: 1
Reputation: 3171
There are a couple ways you could go about this, and I'm not guaranteeing this is the best, but you here's the outline of a solution. I'll leave the implementation as an excercise so I don't do your homework for you ;-)
First, come up with a regular expression to greedily match digits (like you already have) and compile it using Java's Pattern class.
Then, use a Matcher and its replaceFirst method to replace the matching pattern with the empty string. What results will be a string that starts with the first non-numeric character and goes until the end of the input String.
Then, you can see whether the input was valid by seeing if the "mismatched tail" is empty.
Finally, if the input was invalid, use index of with the input string and this "mismatched tail" to tell the user where the first bad character was.
Here's an outline with some "left as an excercise". Each "excercise" is a one-liner. You should be able to find everything you need in the linked documentation for Pattern, Matcher, and String.
public static void main(String[] args){
String myStr = "0123f5";
//Excercise: compile a greedy number matching regex
//Excercise: get an instance of a matcher for this regex and the input string
//replace the first match in input string to greedy
//number-pattern with empty string
String mismatchedTail = m.replaceFirst("");
if(!mismatchedTail.equals("")){
System.out.println("Must enter numeric value at index: "/*Excercise: use index of, the mismatch tail, and input to get the first invalid index*/));
} else {
System.out.println("Good 2 go");
}
}
Result when I run it with the empty parts filled in:
Must enter numeric value at index: 4
Upvotes: 0