请注意,您举报我的问题是重复之前,我引用了这个问题:What's the best way to check if a String represents an integer in Java?
我试图检查其来自代表邻接矩阵的图形类的图形对象。
我使用增强的for循环中的曲线图的每个节点遍历,并且然后使用一个嵌套增强的for循环,以然后遍历从每个节点到每个其它节点的每个连接边缘。
事情是,我处理与具有非整数值的边缘一些图只具有整数值的边缘,以及一些图表。
所以,我需要写一个方法或一系列可以检查,看看是否在一个图形对象的每条边包含的可解析为整数或不字符串的方法。
我的代码是非常简单和基本的,但使用的是应该返回false图的例子时,我得到只有一个真正的返回值。
我的代码如下:
//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;
}
邻接矩阵图形看起来是这样的:
~ 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
这应该返回false,但由于某种原因,它总是返回true。任何帮助将非常感激。谢谢
编辑:positive_int_edges是我设置为true默认我的图形对象的布尔属性。我的希望是穿越一系列的边缘,直到第一个实例中发现,其中一个字符串不能被解析为一个int,一审被发现后,我想停止搜索,因为我不再需要担心剩余的状态尚未被遍历边缘。
编辑#2这是我正在试图调用在我的驱动程序类我的方法:
System.out.println("\nthe parsability of graph g after call to parsability method is: \n");
g.checkParsability();
System.out.println(g.isPositive_int_edges());
首先:如果你在实际的数值不感兴趣,可能更容易使用正则表达式:
final static Pattern IsIntegerPattern = Pattern.compile("^\\d+$");
public boolean isInteger(String str) {
return IsIntegerPattern.matcher(str).matches();
}
这避免产生和捕捉不必要的例外。
关于其结果是true
所有的时间:这不是真的。它将返回false
如果最后进入边缘不是一个数字,因为你遍历所有的边缘,并检查他们是否是整数,但如果你达到了非整数值的边缘不破环。具有有效的整数值连续边缘将“覆盖”的信息。
所以您的实现应该是这样的:
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;
}