1

Please note that before you flag my question as duplicate, I am referencing this question: What's the best way to check if a String represents an integer in Java?

I am attempting to check graph objects which come from a graph class representing adjacency matrices.

I am using an enhanced for loop to iterate over every node in a graph, and then using a nested enhanced for loop, to then iterate over every connecting edge from each node to each other node.

The thing is that I'm dealing with some graphs that have only integer value edges, and some graphs which have non-integer valued edges.

So, I need to write a method or series of methods that can check to see if every edge in a graph object contains strings that are parsable as integers or not.

My code is very simple and basic but when using graph examples that should return false, I am getting only a true return value.

My code is as follows:

//method to determine if a string can be parsed as an integer greater than zero

public boolean isInteger(String str)
{
    try
    {   //if the string can be parsed as an int that's greater than zero...
        Integer.parseInt(str);
            return true;
    }
    catch(Exception e)
    {
        return false;
    }
}

//method to traverse all edges in a graph object to identify whether or not all 
//edges can be parsed as positive integers representing distances 
public void checkParsability()
{
    //while positive int edges is true and therefore all edges can be parsed as positive integers
    if (positive_int_edges)

    {
        for (Node n : this.nodeList)
        {
            for (Edge a : n.getOutgoingEdges())
                this.setPositive_int_edges(isInteger(a.getLabel()));
                //positive_int_edges = isInteger(a.getLabel());

            for (Edge a : n.getIncomingEdges())
                this.setPositive_int_edges(isInteger(a.getLabel()));
                //positive_int_edges = isInteger(a.getLabel());
        }
    }
    //return positive_int_edges;
}


public boolean isPositive_int_edges() {
    return positive_int_edges;
}

public void setPositive_int_edges(boolean positive_int_edges) {
    this.positive_int_edges = positive_int_edges;
}

The adjacency matrix graph looks something like this:

~          val  AAA   BB    C  DDD    E
Alfa         S    ~    >    ~   99  fig
Bravo       67  999  -42    3    x   ==
Charlie      ~    ~    4    ~   yz    9
Delta       4e    3   22    x    ~  !=2
Echo       yes    ~    ~    ~  d>e   33

this should return false but for some reason it is always returning true. Any help would be immensely appreciated. thanks

Edit: positive_int_edges is a boolean attribute of my graph objects which I set to true as default. My hope is to traverse a series of edges until the first instance is found in which a string cannot be parsed as an int, after the first instance is found I want to stop searching since I no longer need to worry about the status of the remaining edges that haven't yet been traversed.

Edit #2 This is how I'm attempting to invoke my methods in my driver class:

System.out.println("\nthe parsability of graph g after call to parsability method is: \n");



g.checkParsability();

System.out.println(g.isPositive_int_edges());
Trixie the Cat
  • 317
  • 3
  • 18
  • So you're saying that `Integer.parseInt("~")` does not throw an exception? – takendarkk Feb 05 '19 at 21:18
  • @csmckelvey No, I'm not getting any indications of exceptions being thrown, possibly because of the catch block? – Trixie the Cat Feb 05 '19 at 21:23
  • It has to throw exception. EDIT: Can you please add a `System.out.println(str)` inside `try` and make sure all of them are printed? – kk1957 Feb 05 '19 at 21:24
  • If an exception is thrown then the catch block will return false which you said is not happening. That would mean that something like `Integer.parseInt("~")` is not throwing an exception which is wrong - it _does_ throw an exception. Basically, I can't recreate what you are describing. – takendarkk Feb 05 '19 at 21:25
  • Most likely you code is not being called for all the inputs. – kk1957 Feb 05 '19 at 21:26
  • If I understand correctly, you want to stop searching after you find a non-integer string in your graph right? It seems that you aren't breaking after an instance of false is returned though, just setting the value repeatedly in a loop over all your graph edges. If that is the case, then whatever edge is evaluated last in your loop would determine whether your `positive_int_edges` value is true or false. – Stalemate Of Tuning Feb 05 '19 at 21:42
  • @csmckelvey okay when I add the following print statement "exception thrown should return false"; to my catch block, just above the return statement, then the print statement executes for almost every single edge which indicates that exception are indeed getting thrown, so it appears that the problem is simply that my attempt to set the boolean value 'positive_int_edges' is not working – Trixie the Cat Feb 05 '19 at 21:48
  • You are not checking it often enough - you check if it is true, then you run the entire loop on all the elements without checking if it turned false. If 1 character is bad and sets that variable to false, but the next character is fine, then it goes back to true and you never noticed that it was false because it was not checked. – takendarkk Feb 05 '19 at 21:50
  • @StalemateOfTuning yes, that's correct. I don't want to continue checking the graph once I find a single non integer value. I do understand your suggestion. For what it's worth, directly below the 'checkParsability' method signature, the very next line: if(positive_int_edges) was actually originally a while statement: while(positive_int_edges) however I changed it to an 'if' statement because with the while statement I wasn't getting any output at all not even a "true" value – Trixie the Cat Feb 05 '19 at 21:51
  • @csmckelvey You are right, thank you. When I move the 'if' statement that checks the value of 'positive_int_edges' into the furthest nested loops that check each edge, I do indeed get a value of false. Thank you again, if you'd like to post an answer I will select it as the best answer. Cheers! – Trixie the Cat Feb 05 '19 at 22:01
  • I am on mobile so it is tough to format answers correctly with code but I will try to post one when I get to a regular machine. – takendarkk Feb 05 '19 at 22:04

1 Answers1

1

First of all: If you're not interested in the actual numeric value, it might be easier to use regular expressions:

final static Pattern IsIntegerPattern = Pattern.compile("^\\d+$");

public boolean isInteger(String str) {
    return IsIntegerPattern.matcher(str).matches();
}

This avoids unecessary exceptions being raised and catched.

About the result being true all the time: That's not actually true. It will return false if the last incoming edge is not a number because you iterate over all edges and check if they are integers but don't break the loop if you reach an edge with a non-integer value. Subsequent edges with valid integer values will "overwrite" that information.

So your implementation should look like this:

public void checkParsability()
{
    //while positive int edges is true and therefore all edges can be parsed as positive integers
    if (positive_int_edges)

    {
        for (Node n : this.nodeList)
        {
            for (Edge a : n.getOutgoingEdges()) {
                this.setPositive_int_edges(isInteger(a.getLabel()));
                //positive_int_edges = isInteger(a.getLabel());
                break;
            ]

            for (Edge a : n.getIncomingEdges()) {
                this.setPositive_int_edges(isInteger(a.getLabel()));
                //positive_int_edges = isInteger(a.getLabel());
                break;
            }
        }
    }
    //return positive_int_edges;
}
Lothar
  • 5,323
  • 1
  • 11
  • 27