Regex to print out all the matches inside ? and , or ) - java

I have a collection of Strings saved in 2d array.
the string has a shape of horn-clause and the complete one string can be in the form of patient(?x) as well as hasdoctor(?x,?y)
if i write the ?x=alex and ?y=john then the above string takes a structure of
patient(alex)
hasdoctor(alex, john)
Now the Question is when is use the below code it finds the ?x, but in the hasdoctor(?x,?y) it skips the ?y .
void find_var(String[][] temp)
{
System.out.println(temp.length);
System.out.println(temp[0].length);
for(int i=0;i<temp.length;i++)
for(int j=1;j<temp[0].length-1;j++)
{
String text_to_parse=temp[i][j];
Pattern y = Pattern.compile("[?]\\w[,)]");
Matcher z= y.matcher(text_to_parse);
if(z.find())
{
System.out.println("Found at::"+temp[i][j]);
System.out.println(z.group());
}
else
{
System.out.println("Not found at::"+temp[i][j]);
}
}}
the pesudo code i can explain that i want in java is
if([?]\\w[,) is found in array[][])
if([?]\\w[,) is already in other_array[]
Then skip;
else
save [?]\\w[,) to other_array[]

Can't say that I completely understand what you're trying to achieve, but I think the problem is that you're using
if (z.find()) { /* ... */ }
instead of
while (z.find()) { /* ... */ }
Using if, the string will not be completely consumed and it will return after the first match is found.

Related

Java: Style-Correcting Code: finding comment

I'm writing these algorithms for a style-correcting program which makes adjustments to a java source file, that can compile without error. It is currently set to read the file line-by-line.
Right now, I'm having trouble writing 2 methods/algorithms which
Determine if the current line (string) has comments, and
finds where the comment starts
I currently have:
public static int FindComment (String TextLine) {
int EndOfCode = TextLine.lastIndexOf("; ");
return TextLine.indexOf("//", EndOfCode);
}
public static boolean HasComment (String TextLine) {
if (TextLine.contains("//"))
{
return true;
}
else
{
return false;
}
}
I know this is incorrect because I can have code, and comments, which contain " ; // ; //" as well as comments. I tried other conditional statements without success.
Hello you don't explain what problem do you have but I think you should escape with backslash characters when working with indexOf function.

Create a linked-list of characters on a stack?

I have an assignment that I'm struggling with.
Write code based on referenced-based stack to implement the balance check of a user input string with ‘{’, ‘}’, ‘(’, ‘)’, and ‘[’, and ‘]’. For instance, if user inputs “(abc[d]e{f})”, your code should say that the expression is balanced.
I have the functions push / pop already written:
public void push(Object newItem) {
top = new Node(newItem, top);
} // end push
public Object pop(){
if (!isEmpty()) {
Node temp = top;
top = top.getNext();
return temp.getItem();
} else {
System.out.print("StackError on " +
"pop: stack empty");
return null;
} // end if
} // end pop
However, what I am struggling with is understanding how to create a new node for each character. Could somebody please help me?
Since your assignment instructions ask you to "Write code based on referenced-based stack", it seems your question is more about how to convert each of user's input string into a node. In that case, you can convert them first to a list of chars simply like this:
public class Main {
public static void main(String[] args){
String str = new String("[(a)bcde]");
System.out.println(str.toCharArray());
}
}
And then use ASCII table to tell whether it's a special character. eg: in above code:
(int) str.toCharArray()[0] // will show ASCII code of '[', 91
Some useful implementations about Reference-based Stack
The isbalanced mechanism simplified for [,],(,):
Always add(push) a [, or (
When you get to a ) check the last added character was a (. If it was remove(pop) it, otherwise mark as unbalanced.
When you get to a ] check the last added character was a [. If it was remove(pop) it, otherwise mark as unbalanced.
If the stack is empty by the end of the string, it is balanced.
In reponse to your comment
Based off an answer for iterate through the characters of a string
unbalanced=false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c.equal('[')
{
push(c);
}
if(c.equal(']')
{
Char tmp = (Char)pop();
if(!tmp.equals('['))
unbalanced=true;
break;
}
}
}
if(pop()!=null)
{
unbalanced=true;
}
Here is what the professor was looking for:
... }
if(currChar.equals("["))
{
myStackRef.push("[");
}
if(currChar.equals("}") && myStackRef.peek().equals("{"))
{
myStackRef.pop();
}
if(currChar.equals(")") && myStackRef.peek().equals("("))
{
myStackRef.pop();
}
if(currChar.equals("]") && myStackRef.peek().equals("["))
{
myStackRef.pop();
}
}
if(myStackRef.isEmpty())
{
System.out.println("Balanced");
}
else
{
System.out.println("Unbalanced");
}
}
}

Java Palindrome Program (am I on track)?

I have only 6 months of Java experience (and I'm also new here) so please bear with me if things don't look entirely right in my code. Please note that it's still a work in progress. I'm trying to write a program that takes in strings and prints only the ones that are palindromes.
I'm supposed to:
- create a method named isPalindrome, which has a String parameter and
- returns a Boolean based on whether the string is a palindrome or not. Then
- modify the main method to use isPalindrome to print only the palindromes.
For example, if I type: "madam James apple mom timer", it should print "madam" and "mom".
This is basically the program I am trying to write:
Ex: Let's use the word "madam". The program will check if the first and last letters match ("madam"). If that is true, then it'll check the next letters, this time "a" and "a" ("madam). And so on and so forth.
This is the Java code I have so far:
public class Palindrome
{
private String theWord; //Error: The value of the field Palindrome.theWord is not used
public boolean isPalindrome( String theWord ) {
int firstPointer = 0;
int secondPointer = theWord.length() - 1;
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved or is not a field
return true;
}
return false;
}
}
public static void main( String[] theWord ) {
Palindrome = new Palindrome( ); //Error: Palindrome cannot be resolved to a variable
for ( int i = 0; i < theWord.length; i++ ) {
while (firstPointer < secondPointer) { //Error: "firstPointer" cannot be resolved to a variable. "secondPointer" cannot be resolved to a variable
if ( theWord.charAt[0] == theWord.charAt (theWord.length() - 1) ) { //Error: charAt cannot be resolved to a variable or is not a field. Cannot invoke length() on the array type String[]
firstPointer++; //Error: "firstPointer" cannot be resolved to a variable
secondPointer++; //Error: "secondPointer" cannot be resolved to a variable
}
System.out.println(theWord);
}
}
}
}
Any bit of help knowing where I've gone wrong would be greatly appreciated. Please don't just give me the right code. I would like to figure this out. Thank you very much.
**EDIT: I've included the errors as comments in the code now. I'm using Eclipse by the way.
-->**EDIT 2: Okay guys. I've read most of your answers and have been able to correct most of my code so far (Thank you all so much so far). The only part I'm still having an issue with right now is this part:
if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1) ) {
leftPointer++;
rightPointer--;
I'm now getting a "Cannot invoke charAt(int) on the array type String[]"
and "Cannot invoke length() on the array type String[]".
Those are the only two errors remaining, then I'll test the code out. I've been trying to resolve them for a while now but I'm still not entirely sure what those errors mean.
Eclipse is suggesting that I change theWord.charAt(i) to theWord.length which is not what I want. It is also suggesting I remove "( )" from length but I don't think that's right either.
Looking at your isPalindrome method :
if ( theWord.charAt(0) == theWord.charAt (theWord.length() - 1)
here you always compare the first character to the last character. In each iteration you should compare a different pair of characters, until you find a pair that doesn't match, or reach the middle of the word.
You should use the i variable of your loop :
if ( theWord.charAt(i) == theWord.charAt (theWord.length() - i - 1)
And the return value should be the exact opposite. If you find a pair of characters that don't match, you return false. Only if the loop ends without returning false, you return true.
Okay, let's break everything down into little sizable chunks.
Input a string
Parse the string, check if it is a palindrome.
Print out the words in the string which were palindromes.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = scan.nextLine(); // 1.
String[] words = sentence.split(" ");
for (String word : words) { // 3.
if (isPalindrome(word)) {
System.out.println(word);
}
}
}
/**
* Check if the string is a palindrome.
* #param string
* #return True if string is palindrome.
*/
public static boolean isPalindrome(String string) { // 2.
for (int i = 0; i < string.length() / 2; i++) {
if (string.charAt(i) != string.charAt(string.length() - i - 1)) {
return false;
}
}
return true;
}}
Some explanation
The method/function isPalindrome is static because we are calling it from a static context, that is the main function. If you want to use it non-statically you would place it in a class and create a object from that class. The rest should be understandable. :-)
A better isPalindrome method
The shortest way is probably just following the definition:
If you reverse the string, and it's still the same, then it's a palindrome:
public static boolean isPalindrome(String input)
{
String reverse = new StringBuilder(input).reverse().toString();
return input.equalsIgnoreCase(reverse);
}
But if there is an educational goal (?), and iterators should be used for some reason then, imho it makes more sense to iterate from the outside towards the inside of the string.
public static boolean isPalindrome(String input)
{
int length = input.length();
for (int i = 0; i < length/2 ; i++)
{
if (input.charAt(i) != (input.charAt(length-1-i))) return false;
}
return true;
}
Phrase parsing
In your example you used the input of the main String[] parameter. Here is just some information in case you wanted to split it to words manually.
Equivalent to what you got now:
String[] words = phrase.split("\\s+");
for (String word : words)
{
// do stuff
}
The split method uses a delimiter to split a String into a String[]. The delimiter \\s is a regex that represents all kinds of whitespace (not only spaces, but also tabs, new-line characters, etc ...).
But it's not perfect (and neither is your way), there can still be commas, dots and other marks in the phrase. You could filter these characters in an iteration, using the Character.isLetterOrDigit method. Alternatively, you could just perform a replace(...) to remove comma's, points and other marks. Or you could use more complex regular expressions as well.
About your code
The first error message : "The value of the field is not used".
The error message is caused by the global private field theWord, because it is never used. It's not used because you also have a parameter with the same name inside the method isPalindrom(String theWord). Whenever you reference theWord inside that method, it will always give advantage to method arguments before considering global variables.
It looks like you are stuck here with a design contradiction.
What exactly is the class Palindrome ? There are 2 options:
Is it supposed to be a toolbox like the Math class ? like boolean value = Palindrome.isPalindrome("madam");?
Or is it supposed to be an Object that you instantiate using a constructor ? like boolean value = new Palindrome("madam").isPalindrome();
Option 1: a toolbox:
public class Palindrome
{
// removed the private field theWord
// make this method static !!
public static boolean isPalindrome( String theWord ) {
...
}
public static void main( String[] theWord ) {
// remove the Palindrome object
// inside the loop check use the static method
// which does not require an object.
if ( Palindrome.isPalindrome(word))
{
}
}
}
Option 2: an object
public class Palindrome
{
// keep the private field theWord
private String theWord;
public Palindrome(String theWord)
{
// set the value of the argument to the private field
this.theWord = theWord;
}
// don't make this method static
// also you don't need the parameter any more.
// it will now use the global field theWord instead of a parameter.
public boolean isPalindrome() {
...
}
public static void main( String[] theWord ) {
// inside the loop check use an object
Palindrome palindrome = new Palindrome(word);
if ( palindrome.isPalindrome())
{
}
}
As for the errors about the firstPointer and secondPointer. You need to define and initialize those variables. I.e. put int firstPointer = 0; before the loop.
In the loop check it out this way:
boolean isPalin = true;
for ( int i = 0; i < theWord.length( )/2; i++ ) { // loop goes till half since no need to check after that
if ( !(theWord.charAt(i) == theWord.charAt (theWord.length() - 1 - i)) ) { // will check each letter with each end letter
isPalin = false;
break;
}
}
return isPalin;
Another things to add -
1 -firstPointer secondPointer are local variables to isPalindrome
2 - When u have decalared theWord as global variable there doent seems a need to pass it. You can use it within the same class.
3 - theWord in main(String[] theWord) would require you to provide input as arguments, it better you go for console input at runtime.
4 - In main you should split each word and pass it to isPalindrome. In your code you are not calling isPalindrome to check anywhere.

Substring a string based on presence of a character

I have a string: LOAN,NEFT,TRAN. I want to substring the string based on getting a , during traversing the string. So I tried to first get a count for how many , are there. but not sure what function to user to get what I want. Also this should be dynamic, meaning I should be able to create as many substrings as required based on number of ,s. I tried the following code:
package try1;
public class StringTest {
public static void main(String[] args) {
String str="LOAN,NEFT,TRAN";
int strlen=str.length();
int count=0;
for(int i=0;i<strlen;i++)
{
if(str.contains("'"))
count++;
}
System.out.println(""+count);
for (int j=0;j<count;j++)
{
//code to create multiple substrings out of str
}
}
}
But I do not think contains() is the function I am looking for because value of count here is coming 0. What should I use?
Your code doesn't actually count the , characters because 1) contains doesn't take into account your loop variable 2) it's searching for ', not ,
Assuming you want to work at a low level rather than using high level functions like .split(), then I'd recommend the following.
for(char c : str.toCharArray()) {
if (c == ',') {
count++;
}
}
You can use split to get substrings directly:
String[] substrings = str.split(",");
Is this what you want as an output: (shown below)?
["LOAN", "NEFT", "TRAN"] // Array as an output
Or to just get the count of the splitting char, you can use the same line as above with this:
int count = substrings.length - 1;

Java algorithm palindrome&

/**
* #(#)palindrome1.java
*
* palindrome1 application
*
* #author
* #version 1.00 2013/11/15
*/
public class palindrome1 {
static boolean isPalindrome(String str) {
int count=0;
//check all characters of sequence is palindrome
for(int i = 0; i < str.length();i++)
{
if(str.charAt(i)!=str.charAt(str.length()-1-i))
{
return false;
}
}
//if it is return true otherwise return false
return true;
}
public static void main(String[] args) {
// TODO, add your application code
String sentence= "bob gave that pop race car to me." ;
String sentenceMax="";
String sentenceNew="";
sentence = sentence.replace( " ","");
for(int i = 0;i<sentence.length();i++)
{
for(int k=0;k<i;k++)
{
sentenceNew = sentence.substring(k,i);
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
{
sentenceMax=sentenceNew;
sentenceNew="";
}
}
}
System.out.println(sentenceMax);
}
}
The question is:t should ask a sentence from user and find the longest palindrome substring in the sentence ignoring the spaces in the sentence and print the longest palindrome substring. You MUST use the function you wrote in Part B. The sentences must be case-insensitive.
and part B is the first method named isPalindrome() in mycode.
The output should be:
racecar
but my code outputs:
e
What is wrong at my code?
You have in your code :
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
And ; is at the bad place. Since it is there it treats it as a if with an empty block, so your real block {} is calculated all the time.
It should be:
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length())
You are assigning a new value to sentenceMax each iteration. Try this instead
sentenceMax += sentenceNew;
Why did you not use the StringBuffer methods ?
StringBuffer.reverse() can reverse the String
after that you can search each substring in the reverted Source string using StringBuffer.indexOf(subString).
Isnt that a much simpler approach ?

Categories

Resources