I am trying to capture allowed and disallowed rules of robots.txt file in java using following code:-
package robotest;
public class RoboTest {
public static void main(String[] args) {
String robo="user-agent:hello user-agent:ppx user-agent:bot allow:/world disallow:/ajax disallow:/posts user-agent:abc allow:/myposts/like disallow:/none user-agent:* allow:/world";
String[] strarr=robo.split(" ");
String[] allowed={};
String[] disallowed={};
boolean new_block=false;
boolean a_or_d=false;
for (String line: strarr){
if(line!=""){
if(line.contains("user-agent:pp")==false && a_or_d){
break;
}
if (line.contains("user-agent:ppx")||(new_block )){
new_block=true;
System.out.println(line);
if(line.contains("allow") || line.contains("disallow")){
a_or_d=true;
}
if(line.contains("allow:")){
//append to allowed
}
if(line.contains("disallowed")) {
//append to disallowed
}
}
}
System.out.println(allowed);;
}
}
}
The code does not works properly as I expect. The rules of robots.txt string is separated by white space. I want to capture rules of user-agent ppx. The code should look for allow or disallow block after discovering user-agent:ppx and append them to list. But it is not working and is confusing too. I am also new to regex in java. What can be solution for this.
Some minimum modifications to your code:
String robo = "user-agent:hello user-agent:ppx user-agent:bot allow:/world disallow:/ajax disallow:/posts user-agent:abc allow:/myposts/like disallow:/none user-agent:* allow:/world";
String[] strarr = robo.split(" ");
Set<String> allowed = new HashSet<>();
Set<String> disallowed = new HashSet<>();
Pattern allowPattern = Pattern.compile("^allow:\\s*(.*)");
Pattern disallowPattern = Pattern.compile("^disallow:\\s*(.*)");
boolean isUserAgentPpx = false;
boolean a_or_d = false;
for (String line : strarr) {
line = line.trim();
// Skip empty lines
if (line.isEmpty()) continue;
if (line.startsWith("user-agent:")) {
// If previous lines were allowed/disallowed rules, then start a new user-agent block
if (a_or_d) {
a_or_d = false;
isUserAgentPpx = false;
}
// Skip block of user-agent if we already found 'user-agent: ppx' or 'user-agent: *'
if (isUserAgentPpx) continue;
if (line.matches("^user-agent:\\s*(ppx|\\*)$")) {
isUserAgentPpx = true;
}
continue;
}
// Process block of allow/disallow
a_or_d = true;
if (isUserAgentPpx) {
Matcher allowMatcher = allowPattern.matcher(line);
if (allowMatcher.find()) {
allowed.add(allowMatcher.group(1));
}
Matcher disallowMatcher = disallowPattern.matcher(line);
if (disallowMatcher.find()) {
disallowed.add(disallowMatcher.group(1));
}
}
}
System.out.println("Allowed rules for Ppx:");
for (String s : allowed) {
System.out.println(s);
}
System.out.println("Disallowed rules for Ppx:");
for (String s : disallowed) {
System.out.println(s);
}
I'm using Set<String> to store the rules to avoid duplicates.
I made it little easy. Beware of edge conditions though
public class RoboTest {
public void test() {
String robo = "user-agent:hello user-agent:ppx allow:/aellow disallow:/deasllow disallow:/posts user-agent:bot allow:/world disallow:/ajax disallow:/posts user-agent:abc allow:/myposts/like disallow:/none user-agent:* allow:/world";
String[] strarr = robo.split(" ");
List<String> allowed = new ArrayList<>();
List<String> disAllowed = new ArrayList<>();
boolean checkAllowed = false;
for (String line : strarr) {
if (line.contains("user-agent:ppx")) {
checkAllowed = true;
continue;
} else if (checkAllowed) {
if (line.contains("disallow:")) {
disAllowed.add(line.split(":")[1]);
continue;
}
if (line.contains("allow:")) {
allowed.add(line.split(":")[1]);
continue;
}
checkAllowed = false;
}
}
System.out.println("Allowed" + allowed);
System.out.println("DisAllowed" + disAllowed);
}
}
Related
Is there a way to create a regex, that will check for proper 'closure' of a checkstyle (which begins with //)?
// CHECKSTYLE:OFF
protected void doSomething() {
}
// CHECKSTYLE:ON
// CHECKSTYLE:OFF
protected void doSomethingElse() {
// CHECKSTYLE:ON
}
If there is a typo in the first CHECKSTYLE:ON, the rest of checkstyles will be ignored.
I don't know if a pure regex would be appropriate here. Your problem is the really the stuff with which parsers are concerned. Actually, I don't even know how we would detect // CHECKSTYLE:ON with a typo in it. But, one option here would be to simply scan your file line by line, and fail if we ever encounter two // CHECKSTYLE:OFF in a row. If that happens, then it implies that either the ON checkstyle was completely omitted, or it was mispelled.
static final String CHECK_ON = "// CHECKSTYLE:ON";
static final String CHECK_OFF = "// CHECKSTYLE:OFF";
File file = new File("your_input.ext");
boolean checkstyleIsOn = false;
try {
Scanner sc = new Scanner(file);
int lineNum = 0;
while (sc.hasNextLine()) {
++lineNum;
String line = sc.nextLine();
if (CHECK_OFF.equals(line)( {
if (!checkStyleIsOn) {
System.out.println("Found extra checkstyle off at line " + lineNum);
break;
}
else {
checkStyleIsOn = false;
}
}
if (CHECK_ON.equals(line)( {
if (checkStyleIsOn) {
System.out.println("Found extra checkstyle on at line " + lineNum);
break;
}
else {
checkStyleIsOn = true;
}
}
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
I need to create a parent child relationship for the following string:
((OPERATING_CARRIER='AB' OR OPERATING_CARRIER='EY' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603))))
I have to insert them into a database table as following
ID PARENT_ID ENTITY OPERATOR VALUE
1 OPERATING_CARRIER = AB
2 OPERATING_CARRIER = EY
3 OPERATING_CARRIER = VA
4 3 FLIGHT_NO = 604
5 3 FLIGHT_NO = 603
using the following code
package whereclause;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QueryMatcher {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sa="((OPERATING_CARRIER='AB' OR OPERATING_CARRIER='AB' OR (OPERATING_CARRIER='VA' AND (FLIGHT_NO=604 OR FLIGHT_NO=603))))";
Matcher m = Pattern.compile("\\w+\\s*=\\s*(?:'[^']+'|\\d+)").matcher(sa);
System.out.println("contains "+sa.contains("((("));
Stack<String> in_cond = new Stack<String>();
Iterator<String> iter = in_cond.iterator();
String new_sa=sa;
while(m.find()) {
String aMatch = m.group();
// add aMatch to match list...
System.out.println(aMatch);
in_cond.push(aMatch);
}
System.out.println("string stack is "+in_cond);
int i=0;
for (String new_sa1:in_cond)
{
if(new_sa.contains(in_cond.get(i)))
{
new_sa=new_sa.replace(in_cond.get(i),"&"+i);
System.out.println("String Contains "+in_cond.get(i));
}
i++;
}
System.out.println("new String is "+new_sa);
}
}
i have got to the following output
contains false
OPERATING_CARRIER='AB'
OPERATING_CARRIER='AB'
OPERATING_CARRIER='VA'
FLIGHT_NO=604
FLIGHT_NO=603
string stack is [OPERATING_CARRIER='AB', OPERATING_CARRIER='AB', OPERATING_CARRIER='VA', FLIGHT_NO=604, FLIGHT_NO=603]
String Contains OPERATING_CARRIER='AB'
String Contains OPERATING_CARRIER='VA'
String Contains FLIGHT_NO=604
String Contains FLIGHT_NO=603
new String is ((&0 OR &0 OR (&2 AND (&3 OR &4))))
But now I am clueless on how to proceed, need help.
I have managed to solve it using following code for splitting the string
and to build the parent child relationship:
String input="name = 'name_1' AND in_stock IN {'in_stock_1','in_stock_2'} AND ( price BETWEEN '01-jan-2015' and '31-may-2015' OR price = 'price_3' )";
String sa =input;
String[] arr = sa.replaceAll("[()]+","").split("\\s*(\\sOR|\\sAND)\\s*");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
String og_st=orig_input;
Stack<String> temp_bool=new Stack<String>();
String[] bool_arr = og_st.split("\\s+");
String[] bool_op=new String[inout.length-1];
for(String bool:bool_arr)
{
if(bool.equals("AND") || bool.equals("OR"))
{
temp_bool.push(bool);
}
else
{
//nothing here
}
}
for (int i=0;i<temp_bool.size();i++)
{
bool_op[i]=temp_bool.get(i);
}
Conditions c=new Conditions();
String[] arr=null;
arr=inout;
//Stack<String> arr2 =new Stack<String>();
String[] atr=null;
if(arr[l].contains(" BETWEEN "))
{
atr=arr[l].split(" BETWEEN ");
c.id=l+1;
c.entity=atr[0];
c.operator=" BETWEEN ";
String c_value=atr[1];
//c_value=c_value.replace("'","");
c.value=c_value;
}
else
{
atr=arr[l].split(" ");
c.id=l+1;
c.entity=atr[0];
c.operator=atr[1];
String c_value=atr[2];
//c_value=c_value.replace("'","");
c.value=c_value;
}
/*for(int k=0;k<arr2.size();k++)
{
if(arr[l].contains(" BETWEEN "))
{
System.out.println("inside if");
atr=arr[l].split(" BETWEEN ");
c.id=l+1;
c.entity=atr[0];
c.operator=" BETWEEN ";
String c_value=atr[1];
c_value=c_value.replace("'","");
c.value=c_value;
System.out.println(c.entity+" "+c.operator+" "+c.value );
}
else
{
System.out.println("inside else");
atr=arr[l].split(" ");
for(int o=0;o<atr.length;o++)
{
arr2.push(atr[o].toString());
}
c.id=l+1;
c.entity=atr[0];
c.operator=atr[1];
String c_value=atr[2];
c_value=c_value.replace("'","");
c.value=c_value;
}
}*/
c.enopva=arr[l];
int c_id=getDecompressedString(arr,orig_input,l);
if (c_id==0)
{
c.parent_id=c_id;
}
else if(c_id>0)
{
c.parent_id=c_id;
}
if(l>=bool_op.length)
{
c.bool_op=null;
}
else if(l<bool_op.length)
{
c.bool_op=bool_op[l].toString();
}
IncentiveProLog.insertLog(" Class has been generated as "+c.toString(),id);
try
{
insertData(c.id,c_id,c.entity,c.operator,c.value,c.bool_op);
}
catch (SQLException e)
{
e.printStackTrace();
}
I have this code that I need to re-write and make a little prettier. It reads lines from a config.txt file and sets variables based on the contents of the file. As you can see, the code is ugly in many ways. There is a lot of duplicated code and the way the program checks the contents of the file is not very elegant (it should probably iterate over the lines instead of checking if the file contains a specific text). Overall, I think it would be nice to avoid having a huge wall of if/else blocks, which actually continues further down but I felt no need to include all of it.
All the program code is written in one main method and I would like to create some classes. I was thinking of a Config class that should handle reading from a config file, and it would have a list of lines (Line objects maybe?) and handle them in order. I've been reading about things like Strategy pattern and Command pattern recently and would like to apply something like that to this case, but I'm unsure any of that is appropriate here. If anyone experienced has any input on this I would greatly appreciate it!
...
try {
reader = new BufferedReader(new FileReader(pathToConfig));
line = reader.readLine();
while(line!=null){
if(line.contains("//")|| line.equals(""));
else{
if(line.contains("inputFolderPath")) {
pathToFolder=line.split("=")[1];
}
else if(line.contains("defaultOutputPath")){
defaultOutputPath=line.split("=")[1];
}
else if(line.contains("checkStyleAttribute")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkStyle=Boolean.parseBoolean(lineAfterSplit);
errorListStyleAttribute=new ArrayList<String>();
}
else if(line.contains("checkXrefAndNormalLinks")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkXref=Boolean.parseBoolean(lineAfterSplit);
errorListXref = new ArrayList<String>();
}
else if(line.contains("checkThatAllTopicsHaveConceptKeywords")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkThatAllTopicsHaveConceptKeywords=Boolean.parseBoolean(lineAfterSplit);
errorListConceptKeywords=new ArrayList<String>();
}
else if(line.contains("checkThatAllTopicsHaveIndexKeywords")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkThatAllTopicsHaveIndexKeywords=Boolean.parseBoolean(lineAfterSplit);
errorListIndexKeywords=new ArrayList<String>();
}
else if(line.contains("checkForNoUIElementsInHeadings")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkForNoUIElementsInHeadings=Boolean.parseBoolean(lineAfterSplit);
errorListUiElements=new ArrayList<String>();
}
else if(line.contains("whatElementToCheckForStyle")){
tag=line.split("=")[1];
if(tag.charAt(0)=='['){
tag=tag.substring(1, tag.length()-1);
String[] tags = tag.split(",");
for(int i=0;i<tags.length;i++){
tagsToCheck.add(tags[i]);
}
}
else if(tag.equals("all")){
checkEveryTag=true;
}
else{
tagsToCheck.add(tag);
}
}
else if(line.contains("checkForProductNamesWithoutDNTTag")&&!line.contains("Path")){
lineAfterSplit=line.split("=")[1];
checkForProductNamesWithoutDNTTag=Boolean.parseBoolean(lineAfterSplit);
errorProductNamesWithoutDNTTag=new ArrayList<String>();
}
... and it just goes on
As i see most of your code is doing repetitive work ( check if like has some text and perform some action on it.)
I suggest you create pluggable matchAndPerform methods. i.e. encapsulate string matching and related method calls into a class (strategy pattern) and have some class where you can dynamically register and remove these matcher objects.
example of strategy pattern:
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
public class OperationMultiply implements Strategy{
#Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
well, I hope this helps
try (BufferedReader reader = new BufferedReader(new FileReader(pathToConfig))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("//") || line.isEmpty()) {
continue;
}
String[] parts = line.split("=", 2);
String key = parts[0].trim();
String value = parts[1].trim();
switch (key) {
case "inputFolderPath":
pathToFolder = value;
break;
case "defaultOutputPath":
defaultOutputPath = value;
break;
case "checkStyleAttribute":
if (!value.contains("Path")) {
checkStyle = Boolean.parseBoolean(value);
errorListStyleAttribute = new ArrayList<>();
}
break;
case "checkXrefAndNormalLinks":
if (!value.contains("Path")) {
checkXref = Boolean.parseBoolean(value);
errorListXref = new ArrayList<>();
}
break;
case "checkThatAllTopicsHaveConceptKeywords":
if (!value.contains("Path")) {
checkThatAllTopicsHaveConceptKeywords = Boolean.parseBoolean(value);
errorListConceptKeywords = new ArrayList<>();
}
break;
case "checkThatAllTopicsHaveIndexKeywords":
if (!value.contains("Path")) {
checkThatAllTopicsHaveIndexKeywords = Boolean.parseBoolean(value);
errorListIndexKeywords = new ArrayList<>();
}
break;
case "checkForNoUIElementsInHeadings":
if (!value.contains("Path")) {
checkForNoUIElementsInHeadings = Boolean.parseBoolean(value);
errorListUiElements = new ArrayList<>();
}
break;
case "whatElementToCheckForStyle":
tag = value;
if (tag.charAt(0) == '[') {
tag = tag.substring(1, tag.length() - 1);
String[] tags = tag.split(",");
for (String t : tags) {
tagsToCheck.add(t.trim());
}
} else if (tag.equals("all")) {
checkEveryTag = true;
} else {
tagsToCheck.add(tag);
}
break;
case "checkForProductNamesWithoutDNTTag":
if (!value.contains("Path")) {
checkForProductNamesWithoutDNTTag = Boolean.parseBoolean(value);
errorProductNamesWithoutDNTTag = new ArrayList<>();
}
break;
default:
// ignore unrecognized keys
break;
}
}
} catch (IOException e) {
// handle exception
}
My project need to parse two type of text data into database.
one format is like this:
<lineNumber>19</lineNumber>
<begin>
2013-08-15,2013-08-15,pek001,123456,08654071,CANX,,,,,,011
<end>
one is like that
<lineNumber>27</lineNumber>
<begin>
2012-11-02,08683683,pek001,00001234,vvip,1
<end>
the difference of the two text is between the begin and end tag.
so our parsing code come out:
first one is:
inputStreamReader = new InputStreamReader(new FileInputStream(FileOne),"gbk"); --different place
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt(StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber。");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
insertFirstToDatabase(line,vo); --just this is different.
}
}
second one is :
inputStreamReader = new InputStreamReader(new FileInputStream(FileTwo),"gbk");
--different place
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
insertSecondToDatabase(line,vo); --only this is different.
}
}
The two piece of code is in two different service code. How can I refactor this reduplicate code? so that each place Just only call one same function to check the lineNumber.
Have the duplicated code in a class that both the other classes either inherit (inheritance) or include a copy of (composition). Alternatively you could even make it a static method in a utility class.
Your code is identical until a single statement, and it's not shown how you determined which of these sequences of code you should be executing, but just move that branching into the if (isDataContent):
// copy/paste from your own, change the if to:
if(isDataContent) {
if (flagFirst) {
insertFirstToDatabase(line,vo); --just this is different.
} else {
insertSecondToDatabase(line,vo); --only this is different.
}
}
Where flagFirst is either a boolean variable or a boolean expression to determine which of the inserts should be done.
You can add 'kind' parameter for selecting usded inserting method as following:
public void process(int kind) {
....
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
if (kind == 1) {
insertFirstToDatabase(line,vo); --just this is different.
}
if (kind == 2) {
insertSecondToDatabase(line,vo); --only this is different.
}
}
}
}
2 things:
duplicated code? - put in static method in utility class
how to differentiate dataContent? -
i. this can be determined while parsing the line depending on the order of fields
(or)
ii. the callee of the static method can determine the same by sending a flag. But this is not good design. You are placing too much implementation i.e. 2 behaviors in a utility method.
(or)
iii. Let the static method parse the XML and return just the line details to the callee. Let the callee handle however it likes. First callee might just want to print, second callee might want to put into db.
So, here it goes,
public static LineDetails parseXML(String filename)
{
inputStreamReader = new InputStreamReader(new FileInputStream(new File(filename));
br=new BufferedReader(inputStreamReader);
lineNumber = 0;
boolean isDataContent = false;
LineDetails lineDetails = new LineDetails();
while (br.ready()) {
String line = br.readLine();
if(line == null){
continue;
}
if(line.contains("<lineNumber>"))
{
try {
lineNumber = Integer.parseInt( StringTools.getDigitalInString(line));
} catch (NumberFormatException e) {
log.error("there is no lineNumber");
}
lineDetails.setLineNumber(lineNumber);
continue;
}
if(line.trim().equals("<begin>"))
{
isDataContent = true;
continue;
}
if(line.trim().equals("<end>"))
{
break;
}
if(isDataContent)
{
// parse line
lineDetails.setLine(line);
}
}
return lineDetails;
}
public class LineDetails
{
private int lineNumber=0;
private String line="";
// getters setters
}
//First callee
methodA()
{
LineDetails lineDetails = parseXML(filename);
if(lineDetails!=null && lineDetails.getLineNumber==19 && lineDetails.getLine()!=null && !lineDetails.getLine.equals(""))
{
insertFirstToDatabase(line);
}
}
//Second callee
methodB()
{
LineDetails lineDetails = parseXML(filename);
if(lineDetails!=null && lineDetails.getLineNumber==27 && lineDetails.getLine()!=null && !lineDetails.getLine.equals(""))
{
insertSecondToDatabase(line);
}
}
I have a java binary search tree and I want to create a menu.
To this day I used StreamTokenizer to get the user input,
But now it doesn't seem to work with "+", "-", "?".
My code:
public void listen() throws IOException {
boolean stay = true;
System.out.println("Give me commands .. ");
while(stay) {
tokens.nextToken();
if(tokens.sval.equals("+")) {
tree.insert(new PositiveInt((int) tokens.nval));
} else if(tokens.sval.equals("?")) {
System.out.println(
tree.retrieve(new PositiveInt((int) tokens.nval)) == null ? "Not exist" : "exist");
} else if(tokens.sval.equals("-")) {
tree.remove(new PositiveInt((int) tokens.nval));
} else if(tokens.sval.equalsIgnoreCase("K")) {
tree.writeKeys();
} else if(tokens.sval.equalsIgnoreCase("E")) {
System.out.println("Empty = " + tree.isEmpty());
} else if(tokens.sval.equalsIgnoreCase("F")) {
System.out.println("Full = " + tree.isFull());
} else if(tokens.sval.equalsIgnoreCase("C")) {
tree.clear();
} else if(tokens.sval.equalsIgnoreCase("P")) {
tree.showStructure();
} else if(tokens.sval.equalsIgnoreCase("Q")) {
stay = false;
} else {
System.out.println("Unaccaptable input.");
}
}
}
When I enter "P" , for example, or any other character, everything's alright.
When I enter "?", "+", "-", I'm getting:
Exception in thread "main" java.lang.NullPointerException
at TestBSTree.listen(TestBSTree.java:27)
at TestBSTree.main(TestBSTree.java:54)
As Line 27 is :
if(tokens.sval.equals("+")) {
In other words, a non-charater is not accaptable with the tokenizer.
Why and how can I fix it?
Whole code:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class TestBSTree {
// Test class variables
BSTree<PositiveInt> tree;
InputStreamReader reader;
StreamTokenizer tokens;
PositiveInt key;
int in;
public TestBSTree(PositiveInt root) {
tree = new BSTree<PositiveInt>(new BSTreeNode<>(root, null, null));
reader = new InputStreamReader(System.in);
tokens = new StreamTokenizer(reader);
key = null;
}
public void listen() throws IOException {
boolean stay = true;
System.out.println("Give me commands .. ");
while(stay) {
tokens.nextToken();
if(tokens.sval.equals("+")) {
tree.insert(new PositiveInt((int) tokens.nval));
} else if(tokens.sval.equals("?")) {
System.out.println(
tree.retrieve(new PositiveInt((int) tokens.nval)) == null ? "Not exist" : "exist");
} else if(tokens.sval.equals("-")) {
tree.remove(new PositiveInt((int) tokens.nval));
} else if(tokens.sval.equalsIgnoreCase("K")) {
tree.writeKeys();
} else if(tokens.sval.equalsIgnoreCase("E")) {
System.out.println("Empty = " + tree.isEmpty());
} else if(tokens.sval.equalsIgnoreCase("F")) {
System.out.println("Full = " + tree.isFull());
} else if(tokens.sval.equalsIgnoreCase("C")) {
tree.clear();
} else if(tokens.sval.equalsIgnoreCase("P")) {
tree.showStructure();
} else if(tokens.sval.equalsIgnoreCase("Q")) {
stay = false;
} else {
System.out.println("Unaccaptable input.");
}
}
}
public static void main(String[] args) throws IOException {
TestBSTree test = new TestBSTree(new PositiveInt(0));
test.listen();
}
}
It doesn't matter how does the tree or PositiveInt implemented, the main issue is the tokenizer.
if you want so split a string containg a '?' or a plus ('+'), you cannot simply use this symbol to split this String; they are reserved 'words' and need a exclude sign '\' which itself needs an exclusion sign ^^ (so you need two '\\' and the special sign)
try to use something like that:
StringTokenizer tokenizer = new StringTokenizer("ghj?klm", "\\?");
System.out.println(tokenizer.countTokens() );
-> result: the count is 2 !
you can also apply this method for String.split("\+");
//wont work!!
String str = "ghj?klm";
String[] s = str.split("?");
System.out.println(s.length );
but this code will work!
String str = "ghj?klm";
String[] s = str.split("\\?");
System.out.println(s.length );
it's the same 'problem' ^^ i hope this helped!
unfortunaltely i don't know which other symbols require a slahs... :-(