I have a quick simple technical problem: I'm trying to read this file:
S,B,C,D,E,F
0,2,1,inf,inf,inf
inf,0,2,inf,inf,inf
inf,inf,0,4,5,inf
inf,1,inf,0,inf,5
inf,inf,inf,inf,0,1
inf,inf,inf,inf,inf,0
and put each elements in some Array:
BufferedReader br = null;
FileReader fr = null;
nodes = new ArrayList<Node>();
edges = new ArrayList<Edge>();
try
{
fr = new FileReader(filePath);
br = new BufferedReader(fr);
String firstLine = "";
String line = "";
String[] words = null;
firstLine = br.readLine();
words = firstLine.split(separtor);
for (int i=0; i<words.length-1;i++)
{
nodes.add(new Node(i, words[i]));
}
int node = 0;
while ((line = br.readLine()) != null)
{
words = line.split(separtor);
for (int i=0; i<words.length-1;i++)
{
if (!words[i].equals("inf") || !words[i].equals("0"))
{
edges.add(new Edge(nodes.get(node), nodes.get(i), Integer.parseInt(words[i])));
}
}
node++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
The problems come in this line : if (!words[i].equals("inf") || !words[i].equals("0"))
When the string is not "inf" or "0" then you start adding stuff but when I actually run, it still add "0" and "inf" causing an error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "inf"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
I did some tests, but I can't still understand why my condition doesn't work.
Thanks in advance.
You have to replace that or
by and and
:
if (!words[i].equals("inf") && !words[i].equals("0"))
With the or
you always will enter the block because words[i]
is always unequal to "inf" or "0". Up to that your condition in your loop is wrong. Replace
for (int i=0; i<words.length-1;i++)
by
for (int i=0; i<words.length;i++)
Otherwise you will miss the last element of each line.
EDIT: you also have to change the condition in the other loop from
for (int i=0; i<words.length-1;i++)
{
nodes.add(new Node(i, words[i]));
}
to
for (int i=0; i<words.length;i++)
{
nodes.add(new Node(i, words[i]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.