This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I wrote the following program. I need to get the number of odd n even numbers from "data.in" file .
I am getting an exception as :Exception in thread "main" java.lang.StringIndexoutofBoundsException : index out of range:-1 at java.lang.String.substring<String.java:1768> at oddeven.main<oddeven.java:23>
data.in file contains :The first data value is 1066 The second data value is 1492 The third data value is 1939 The fourth data value is 1944 The fifth data value is 2000
Ignore the String info since you didn't write that. What's happening at your line 23 with an index that might be -1?
Look up a line to see how it maybe got to be -1. I think your code does not match your input file layout. See if that helps!
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
prerna boja
Ranch Hand
Joined: Aug 19, 2004
Posts: 67
posted
0
Hi ,
I tried to chage the program. It is compiling n giving no exception, but I amnot getting the output.
I tried to chage the program. It is compiling n giving no exception, but I amnot getting the output.
Prerna, I don't think you fixed the problem. In fact, I think it is worse. I believe the reason why you are not getting anymore exceptions is because the code in question is no longer running.
BTW, you should fix the idents. It is very difficult to read.
Your first problem is that the code you've given reads only the first number forever: you never change inputString. Strictly speaking, you can't change it--Strings are immutable--but you could at least replace it with another String that's shorter. If you're just starting out, try the substring() method; if you're feeling fancy, you could do it the correct way, which is by using a StringBuffer.
I have no idea how you got a runtime error with the code you've given; I ran it on my JVM and it just kept reading the first number for ever and ever. But in this context, -1 should indicate either that you've reached end-of-file or that inputString.indexOf(loc) can't find the loc substring.
Whenever you see a -1, you should check the API to see what values your function calls might be returning. In general, beginning Java programmers should always code with the API right in front of them at all times.