Regular Expressions in Java - Checking instance variables start with a capital letter? - java

How am I able to check if both the countryName and capitalName instance variables start with a capital letter? I'm sure I have to use regular expressions involving somthing like this "^[A-Z]" but am not sure how or where to put the full code.
I am a beginner at java and would appreciate any help or suggestions.
java.util.regex.*;
public class CountryInfo {
private String countryName;
private String capitalName;
public CountryInfo (String countryName, String capitalName) {
super();
this.countryName=countryName;
this.capitalName=capitalName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCapitalName() {
return capitalName;
}
public void setCapitalName(String capitalName) {
this.capitalName = capitalName;
}
}

The easiest way is to use the following code
char c = countryName.charAt(0);
if (c >= 'A' && c <= 'Z')
//first character is capital letter!
Withouth using regex, which may be complex for a beginner.
Where to put the code?
Probably in the constructor to check if it's capital letter or not, but you should explain what you need to do if it's a capital letter and what if it isn't to be sure where to put it.

Use this pattern to check:
\b[A-Z]
I don't know what exactly your function is supposed to do when it gets a match, so I can't really tell you where to put it. The most sensible place would probably in the constructor.

Regex based solution as you desired using String#matches(String regex)
Create a new method in the same class as:
public boolean isValidDate() {
boolean valid = true;
if (!this.capitalName.matches("^[A-Z].*$"))
valid = false;
else if (!this.countryName.matches("^[A-Z].*$"))
valid = false;
return valid;
}
Now after creating an instance and populating your object you can call: isValidDate() to know whether data is valid or not.

Related

Better way to invert cases of characters in a string in Java

As a novice Java programmer who barely got started in Java programming, I am totally exhausted in trying to find a solution to this issue. A course that I am currently studying gave homework that asked me to create a Java class that has a sort of “reverse” method that returns a new version of the string
of the current string where the capitalization is reversed (i.e., lowercase to uppercase
and uppercase to lowercase) for the alphabetical characters specified in a given condition. Say if I were to reverse “abc, XYZ; 123.” using reverse("bcdxyz#3210."), it must return "aBC, xyz; 123.". (P.S: the class ignores numbers and special characters and the variable "myString" is where the "abc, XYZ; 123." goes to.). So far, I've only managed to return out "aBC, XYZ; 123." with the code below. Am I missing something here?
public String reverse(String arg) {
// TODO Implement method
String arg_no_sym = arg.replaceAll("[^a-zA-Z0-9]","");
String arg_perfect = arg_no_sym.replaceAll("\\d","");
if (myString != null) {
char[] arrayOfReplaceChars = arg_perfect.toCharArray();
char[] arrayOfmyString = myString.toCharArray();
for (int i = 0; i < arg_perfect.length(); i++) {
myString = myString.replace(String.valueOf((arrayOfReplaceChars[i])), String.valueOf((arrayOfReplaceChars[i])).toUpperCase());
}
return myString;
}
else {
return "";
}
}
How about using the methods isUpperCase() and isLowerCase() to check the case of the letters and then use toUpperCase() and toLowerCase() to change the case of them?

Java method taking 0 arguments and returning a double using if else statements with strings

I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer

I want to check the number of characters in a String method

I want to check that a certain number of characters in a method that inputs and returns string
public static String watsonCrick(String dna){
dna = "ATA";
int length = dna.length();
char firstCharacter = dna.charAt(0);
char secondCharacter = dnaSequence.charAt(1);
char thirdCharacer = dna.charAt(2);
}
This is my code so far but I dont know what to put as my return and I don't know how to call the method from my main method? All I need is to make sure the string "dna" has three characters in it.
The method doesn't return anything as of yet, I really just want to make sure I'm on the right track and this is how I have to restrict the number of characters in my string.
EDIT: Sorry to add one more thing but if I wanted to add a condition to the method, like let's say I already made a boolean method beforehand and wanted to check if the char firstCharacter was true according to the method how would I add it?
I don't know how to call the method from my main method?
Like this:
public static void main(String[] args) {
watsonCrick("ATA");
}
or if the watsonCrick method is in a different class, like this:
public static void main(String[] args) {
OtherClass.watsonCrick("ATA");
}
All I need is to make sure the string "dna" has three characters in it.
You can do this by putting this at the beginning of the watsonCrick method:
if (dna.length() != 3) { throw new IllegalArgumentException(); }
Assing dna variable in Main method and then write just methodName(Parameters) for calling the method in Main. i.e
String dna;
public static void main(String[] args) {
dna = "ATA";
watsonCrick(dna);
}
And if you need to make sure the string has three characters, use this;
public static String watsonCrick(String dna){
int length = dna.length();
if(length == 3) {
return "true";
}
return "false";
}
If you want you can change the return type to Boolen. (True or False)

Modelling a regular expression parser with polymorphism

So, I'm doing a regular expression parser for school that creates a hierarchy of objects in charge of the matching. I decided to do it object oriented because it's easier for me to imagine an implementation of the grammar that way. So, these are my classes making up the regular expressions. It's all in Java, but I think you can follow along if you're proficient in any object oriented language.
The only operators we're required to implement is Union (+), Kleene-Star (*), Concatenation of expressions (ab or maybe (a+b)c) and of course the Parenthesis as illustrated in the example of Concatination. This is what I've implemented right now and I've got it to work like a charm with a bit of overhead in the main.
The parent class, Regexp.java
public abstract class Regexp {
//Print out the regular expression it's holding
//Used for debugging purposes
abstract public void print();
//Checks if the string matches the expression it's holding
abstract public Boolean match(String text);
//Adds a regular expression to be operated upon by the operators
abstract public void add(Regexp regexp);
/*
*To help the main with the overhead to help it decide which regexp will
*hold the other
*/
abstract public Boolean isEmpty();
}
There's the most simple regexp, Base.java, which holds a char and returns true if the string matches the char.
public class Base extends Regexp{
char c;
public Base(char c){
this.c = c;
}
public Base(){
c = null;
}
#Override
public void print() {
System.out.println(c);
}
//If the string is the char, return true
#Override
public Boolean match(String text) {
if(text.length() > 1) return false;
return text.startsWith(""+c);
}
//Not utilized, since base is only contained and cannot contain
#Override
public void add(Regexp regexp) {
}
#Override
public Boolean isEmpty() {
return c == null;
}
}
A parenthesis, Paren.java, to hold a regexp inside it. Nothing really fancy here, but illustrates how matching works.
public class Paren extends Regexp{
//Member variables: What it's holding and if it's holding something
private Regexp regexp;
Boolean empty;
//Parenthesis starts out empty
public Paren(){
empty = true;
}
//Unless you create it with something to hold
public Paren(Regexp regexp){
this.regexp = regexp;
empty = false;
}
//Print out what it's holding
#Override
public void print() {
regexp.print();
}
//Real simple; either what you're holding matches the string or it doesn't
#Override
public Boolean match(String text) {
return regexp.match(text);
}
//Pass something for it to hold, then it's not empty
#Override
public void add(Regexp regexp) {
this.regexp = regexp;
empty = false;
}
//Return if it's holding something
#Override
public Boolean isEmpty() {
return empty;
}
}
A Union.java, which is two regexps that can be matched. If one of them is matched, the whole Union is a match.
public class Union extends Regexp{
//Members
Regexp lhs;
Regexp rhs;
//Indicating if there's room to push more stuff in
private Boolean lhsEmpty;
private Boolean rhsEmpty;
public Union(){
lhsEmpty = true;
rhsEmpty = true;
}
//Can start out with something on the left side
public Union(Regexp lhs){
this.lhs = lhs;
lhsEmpty = false;
rhsEmpty = true;
}
//Or with both members set
public Union(Regexp lhs, Regexp rhs) {
this.lhs = lhs;
this.rhs = rhs;
lhsEmpty = false;
rhsEmpty = false;
}
//Some stuff to help me see the unions format when I'm debugging
#Override
public void print() {
System.out.println("(");
lhs.print();
System.out.println("union");
rhs.print();
System.out.println(")");
}
//If the string matches the left side or right side, it's a match
#Override
public Boolean match(String text) {
if(lhs.match(text) || rhs.match(text)) return true;
return false;
}
/*
*If the left side is not set, add the member there first
*If not, and right side is empty, add the member there
*If they're both full, merge it with the right side
*(This is a consequence of left-to-right parsing)
*/
#Override
public void add(Regexp regexp) {
if(lhsEmpty){
lhs = regexp;
lhsEmpty = false;
}else if(rhsEmpty){
rhs = regexp;
rhsEmpty = false;
}else{
rhs.add(regexp);
}
}
//If it's not full, it's empty
#Override
public Boolean isEmpty() {
return (lhsEmpty || rhsEmpty);
}
}
A concatenation, Concat.java, which is basically a list of regexps chained together. This one is complicated.
public class Concat extends Regexp{
/*
*The list of regexps is called product and the
*regexps inside called factors
*/
List<Regexp> product;
public Concat(){
product = new ArrayList<Regexp>();
}
public Concat(Regexp regexp){
product = new ArrayList<Regexp>();
pushRegexp(regexp);
}
public Concat(List<Regexp> product) {
this.product = product;
}
//Adding a new regexp pushes it into the list
public void pushRegexp(Regexp regexp){
product.add(regexp);
}
//Loops over and prints them
#Override
public void print() {
for(Regexp factor: product){
factor.print();
}
}
/*
*Builds up a substring approaching the input string.
*When it matches, it builds another substring from where it
*stopped. If the entire string has been pushed, it checks if
*there's an equal amount of matches and factors.
*/
#Override
public Boolean match(String text) {
ArrayList<Boolean> bools = new ArrayList<Boolean>();
int start = 0;
ListIterator<Regexp> itr = product.listIterator();
Regexp factor = itr.next();
for(int i = 0; i <= text.length(); i++){
String test = text.substring(start, i);
if(factor.match(test)){
start = i;
bools.add(true);
if(itr.hasNext())
factor = itr.next();
}
}
return (allTrue(bools) && (start == text.length()));
}
private Boolean allTrue(List<Boolean> bools){
return product.size() == bools.size();
}
#Override
public void add(Regexp regexp) {
pushRegexp(regexp);
}
#Override
public Boolean isEmpty() {
return product.isEmpty();
}
}
Again, I've gotten these to work to my satisfaction with my overhead, tokenization and all that good stuff. Now I want to introduce the Kleene-star operation. It matches on any number, even 0, of occurrences in the text. So, ba* would match b, ba, baa, baaa and so on while (ba)* would match on ba, baba, bababa and so on. Does it even look possible to extend my Regexp to this or do you see another way of solving this?
PS: There's getters, setter and all kinds of other support functions that I didn't write out, but this is mainly for you to get the point quickly of how these classes works.
You seem to be trying to use a fallback algorithm to do the parsing. That can work -- although it is easier to do with higher-order functions -- but it is far from the best way to parse regular expressions (by which I mean the things which are mathematically regular expressions, as opposed to the panoply of parsing languages implemented by "regular expression" libraries in various languages).
It's not the best way because the parsing time is not linear in the size of the string to be matched; in fact, it can be exponential. But to understand that, it's important to understand why your current implementation has a problem.
Consider the fairly simple regular expression (ab+a)(bb+a). That can match exactly four strings: abbb, aba, abb, aa. All of those strings start with a, so your concatenation algorithm will match the first concatenand ((ab+a)) at position 1, and proceed to try the second concatenand (bb+a). That will successfully match abb and aa, but it will fail on aba and abbb.
Now, suppose you modified the concatenation function to select the longest matching substring rather than the shortest one. In that case, the first subexpression would match ab in three of the possible strings (all but aa), and the match would fail in the case of abb.
In short, when you are matching a concatenation R·S, you need to do something like this:
Find some initial string which matches R
See if S matches the rest of the text
If not, repeat with another initial string which matches R
In the case of full regular expression matches, it doesn't matter which order we list matches for R, but usually we're trying to find the longest substring which matches a regular expression, so it is convenient to enumerate the possible matches from longest to shortest.
Doing that means that we need to be able to restart a match after a downstream failure, to find the "next match". That's not terribly complicated, but it definitely complicates the interface, because all of the compound regular expression operators need to "pass through" the failure to their children in order to find the next alternative. That is, the operator R+S might first find something which matches R. If asked for the next possibility, it first has to ask R if there is another string which it could match, before moving on to S. (And that's passing over the question of how to get + to list the matches in order by length.)
With such an implementation, it's easy to see how to implement the Kleene star (R*), and it is also easy to see why it can take exponential time. One possible implementation:
First, match as many R as possible.
If asked for another match: ask the last R for another match
If there are no more possibilities, drop the last R from the list, and ask what is now the last R for another match
If none of that worked, propose the empty string as a match
Fail
(This can be simplified with recursion: Match an R, then match an R*. For the next match, first try the next R*; failing that try the next R and the first following R*; when all else fails, try the empty string.)
Implementing that is an interesting programming exercise, so I encourage you to continue. But be aware that there are better algorithms. You might want to read Russ Cox's interesting essays on regular expression matching.

JAVA - Making Constructors, Calling Sets, and Replacing Chars in a String using set Classes

In Java, where should I aim (I enjoy figuring it out myself) to get, with sample data:
I am Sam I am a
the output:
I am Sam I am - letter to remove a
I m Sm I m
Basically, it is to "Remove all instances of the specified removal letter from the original sentence"
As this is for a class, I am limited with what I can do. For this assignment I am stuck with the given classes/constructors and am not allowed to make any more unless it is noted, which in my case, is to create another constructor class; Anyway, that has been the real challenge as it is hard to get help (No matter how many times I've googled!) with it being so specific and I new to the language.
Here is what I was given:
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private char lookFor;
public LetterRemover()
{
//call set
}
//add in second constructor
public void setRemover(String s, char rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
This is what I've done so far:
import java.util.Scanner;
import static java.lang.System.*;
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
//add in second constructor
public void setRemover(String s, String rem)
{
sentence = s;
lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I tried changing the char to a string for the "lookfor" to use the replace all method which seemed after a lot of research and the best way to get the letters out.
Is there any noticeable mistakes and where should I look to fix them? I do not really want the right code, or for anyone to "do" the work for me. I really want to try and figure it out. But I need a little help in pointing in the right direction to get my desired output :)
Let me know if there is any other details or whatnot, this is also , this is also my first time using the site. There were many similar questions to this, but as I really am a beginner I struggled to understand people's explanations
--Edit--
Moving to my runner class, this is what I wrote, trying to get for the desired output. I am not really sure how to deal with output as I really have just started learning to write them myself.
I keep getting a void error though:
import static java.lang.System.*;
public class LetterRemoverRunner
{
public static void main( String args[] )
{
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
}
}
Try the below code and confirm this is what your requirement is.
LetterRemoverRunner.java
public class LetterRemoverRunner {
public static void main(String args[])
{
LetterRemover test = new LetterRemover ();
test.setRemover("I really want dumplings","l");
System.out.println(test.toString());
System.out.println("Removed :"+test.removeLetters());
}
}
LetterRemover.java
public class LetterRemover
{
private String sentence;
private String lookFor;
public LetterRemover()
{
//I am not sure what this means
}
public void setRemover(String s, String rem)
{
this.sentence = s;
this.lookFor = rem;
}
public String removeLetters()
{
sentence = sentence.replaceAll(lookFor,"");
String cleaned=sentence;
return cleaned;
}
public String toString()
{
return sentence + " - letter to remove " + lookFor;
}
}
I'm pleased you suggested you don't want the answer - much better way to learn!
I'm not sure you've understood constructors yet. You're line:
LetterRemover test = new LetterRemover
(test.setRemover("I really want dumplings","l"));
Is going to give you a null pointer error because it's calling setRemover on test before test has been constructed. You should be constructing the object with its sentence and lookFor values before calling setRemover.
Here are some things you might want to look at:
The String.indexOf method will look for a certain character or string and tell you where to find it (or if it isn't in the string at all).
The String.substring method allows you to take part of a string using string positions
You can build a new string by concatenating substrings together
Using a while loop you can continue using indexOf until the target cannot be found.
As you've pointed out, you can also use one of the replace methods to replace the target with "".

Categories

Resources