I'm running a simple java program. I programmed it in Netbeans. Everything worked great. Attempted to transition code to use Ant because that's what my class requires, and I'm getting a weird error.
All text coming in from the .txt is in the format,
Baker William Chavez 04/01/05
Sanchez Jose Chavez 06/15/05
etc ...
There about 20 entries, 3 names and a date. Each entry is on its own line.
I'm using this code to read it in.
while ((line = br.readLine()) != null) {
//formatting data correctly
String [] info = line.split(" ");
for(int i = 0; i < info.length; i++){
System.out.println(info[i]);
}
System.out.println(info[0]);
System.out.println(info[1]); /* this line of code */
}
So every info [] is of length 4. When I run the for loop, it prints out everything exactly as expected. Printing out "info[0]" works exactly has expected.
But for some reason when I attempt to print out "info[1]", I get an
java.lang.ArrayIndexOutOfBoundsException: 1
error. I have no explanation for why this happens. When I don't attempt to print out info[1] by itself, my program works correctly. In the for loop, info[1] gets printed out, because the for loop loops through 4 times. This code worked perfectly in Netbeans, but using Ant is doesn't work.
Does anyone know adding or removing just one line,
System.out.println(info[1]);
causes my program to run or throw an exception?
I'm running Ant 1.9.2
I'm running Java 1.7.0_17
I've checked this multiple times, so I'm pretty sure its not something I've made an erro ron. I'm a fairly experienced programmer, so I pretty confident it's not my error. It runs well in Netbeans. I don't have an explanation for the error.
edit 1.
My code throws an error the second time threw the while loop.
Printing out the info[] length, or the line itself works great with I don't print out line[1] by itself. It stills fails and throws an error when I printout the info[1] by itself.
http://pastebin.com/NAUeDsZH
Edit 2.
#Millie Smith was on the right trail because my .txt file wasn't correctly formatted. Viewing it in notepad for some reason didn't display the extra space in between each line.
http://pastebin.com/njjdSHHZ
My correct pastebin.
I was attempting to use code to strip out all of the blank space, commas, new lines, and such,
line = line.replaceAll("\\s+", " ");
line = line.replaceAll(",","");
line = line.replaceAll("\\n", "");
line = line.replaceAll("\\r", "");
String [] info = line.split(" ");
I incorrectly assumed that that code would take care of any irregularities. I was wrong. So on my first pastebin, I formatted the code to what I thought I was dealing with, which was also incorrect.
So if I test for line.length() > 1, that gives me my results that I am looking for. I'm not an experienced programmer as I think I am.
Your last line of the file is BLANK ( probably just a end of line marker ) and this is causing the last .split(" ") to assign a single element array with nothing in it but an empty string in the first position.
Make sure your file doesn't have a ZERO length line as the last line or any of the lines.
Learn to use the step debugger, it is your best friend, and step through the code and see what line is equal to on the very last iteration.
Ant and Netbeans have nothing to do with this error, it is completely data related and we can't see your entire data file in its native format
Related
So, before I start I just wanted to say that I'm very new to Java as a language and I've been reading a text book that was recommended to me.
One of the examples provided within the text book on for loops had the following code, which is meant to generate an infinite for loop until the user presses the character 'S' on their keyboard.
Here is the code:
class ForTest {
public static void main(String args[])
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for (i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
I copied the code exactly as it was written within the book but when I run the program, to my surprise, it doesn't start printing out numbers onto the console. Additionally, whenever I press any keys on the keyboard it generates three numbers within the sequence. Example shown below:
I have also included a screenshot of the code from the book below:
I was wondering whether anyone knows why this is the case!
Any help would be greatly appreciated thanks.
The reason it's printing multiple times is because multiple characters are detected.
In your case, it's printing twice because you entered a value (Pass 1) and a new line (Pass 2)
The problem you have is not with System.in.read(), but because the console is usually using a buffered approach. Meaning that data is only transferred to the System.in.read() once you press enter.
So to get the example working, you would have to switch the console to an unbuffered mode, but there is no portable way to do this, because there are so much different types of consoles. Maybe have a look at what editor/console the book is using
This block of code looks like it was written by someone who was deliberately trying to make it obtuse and difficult to comprehend for a beginner.
The middle expression of a for statement is the criterion for taking the next step of the loop. It is evaluated before each step of the loop to determine whether the for loop is complete yet. In this case, it calls in.read() and checks if the input is S before each step of the loop.
in.read() waits for the next line of input it gets. When you enter a value and press Enter, that line gets read, so the loop takes a step. And a new line is also entered, so the loop takes a second step.
It will not print lines to the console unless you enter lines, because in.read() causes the program to block (wait) for the next input.
I have a java program that simulates values and returns them. But I want to see how far the simulation is by printing the current state.
Ex:
System.out.print("Number of simulations: ");
for(int i=0;i<NUMBER_OF_SIMULATIONS;i++){
/* Do my calcutions*/
System.out.print("\b" + i);
}
I thougth this was possible, but the output is:
Number of simulations: 0?1?2?3?4?5?6?7?8?9?10?11?12?
I only want to see the current state, so not a counter.
So if i++ current i removes and i+1 will shown.
\b will go back 1 char. As Pawel Veselov said, use \r to go to the beginning of the line.
Another important thing is that, depending on where you're testing the output (IDE), it won't work as expected. You should test in a shell (Windows cmd or Linux terminal) in order to see the real result.
If you where expecting to edit the value to have one line being:
Number of simulations: 0 //and then editing just the number to have
Number of simulations: 1
Its not possible on the command line to my knowledge.. every time you call System.out.print you are writing/adding the value into the "out" stream, hence the count being added every time is called at the end of the line with print().
You would need to add a new line for every time you print it.
System.out.println("Number of Simulations: " + i);
And that will give you a new line everytime.
Edit: Its not what you want, but thats a cleaner way to visualize it and how programs normally log steps.
I'm having some bother with a string array in java. I'm trying to output an inverseNewWords LinkedHashMap value to an output file, but I keep getting an NPE for the array. For some reason the first line doesn't seem to work.
System.out.println(inverseNewWords.get(codeIntegers[i]));
prints out the word fine, but this line:
System.out.println(newWTF[i]);
comes back as null.
newWTF[i] = inverseNewWords.get(codeIntegers[i]);
System.out.println(inverseNewWords.get(codeIntegers[i]));
System.out.println(newWTF[i]);
decodedWriter.write(newWTF[i]);
** EDIT **
Thanks for the quick replies, I've been working on this specific program throughout the night to get it submitted on time, and my head's cracked.
The string array was indeed initialized incorrectly, but now my main problem is showing it's face:
System.out.println(newWTF[i]);
decodedWriter.write(newWTF[i]);
the println statement correctly shows me each word in the array. However, the FileWriter isn't writing the same words to the file. (The Filewriter is being flushed and closed before the program ends)
Any help is greatly appreciated
The only reason why this line
System.out.println(newWTF[i]);
can throw NPE is that newWTF is null
may help :
newWTF = new String[inverseNewWords.size()];
So, today I hit a snag trying to split a string array element which has been split from a long string already.. It works like this:
A string is created from a file. This string is split at blank lines (\n\n) which are basically paragraphs of text, which gets used as body text elsewhere.
Each paragraph begins with a topic, followed by an asterisk, followed by the body text.
Here's the issue -
It would be too simple to, while iterating through each paragraph string element to split these at the asterisk character (escaped, of course). To demonstrate, the first part works well:
sections = formatted.split("\n\n"); //sections previously declared as string array
int lines = sections.length ;
for(int i= 0 ; i< lines; i++) {
sections[i] = "Heading\n\n" + sections[i] ;
Now, when trying to perform another task in each iteration (yes, just join the two code windows together in your mind), it throws NPE on the second resulting index:
String paragraph = sections[i];
String[] half = paragraph.split("\\*");
topics[i] = half[0]; //Topics also previously declared as array
}
The last line inside the iterator throws a NPE (not out of bounds). I can't tell if it's the I or the ) index.
I would really appreciate understanding why this doesn't work. Perhaps it's because I always seem to hit these problems well after midnight...
How can I build these two parallel instance arrays? Thanks!
It seems likely to me that Topics is null - there's nothing within the code you've shown to assign it a non-null value. You probably want:
Topics = new String[lines];
before the loop. You should be able to spot this pretty easily in the debugger, too. (If you're confused about where an NPE is coming from, adding diagnostics and/or debugging are usually the first steps.)
Also note that conventionally your variables would be called sections and topics, as variables in Java are usually camelCased.
I'm in the final stages of testing before I release the alpha version of a program I am writing. This may be a silly question but I just can't seem to figure it out. I understand what drjava is telling me, that I'm missing a variable, but I also don't understand because I never made a variable under the name "()". I'm not even sure you can set any type of variable to a open-close parenthesis. Anyways I was testing and while it works, it doesn't the way I want it to. I entered into the scanner "Mr. B." without the quotes of course. The program did not print the B. I'm thinking it might be the space in between Mr. and B, because other inputs with a space did the same. I can not release a version of my program knowing there is a GIANT glitch in the code. I'm wondering why, and I tried to fix it by changing ownersname.next(); to ownersname.nextLine and ownersname.next and ownersname.nextScanner and ownername.nextScanner. This is where the error comes in, when it says it can't find the variable until I change it back to it's original code, which is below.
Scanner ownersname = new Scanner(System.in);
String sownersname = ownersname.next();
System.out.println(sownersname + "? That is a nice name.");
I'm in the final stages of testing before I release the alpha version of a program I am writing.
You're creating a professional application? Please do tell us more about this.
I understand what drjava is telling me, that I'm missing a variable, but I also don't understand because I never made a variable under the name "()". I'm not even sure you can set any type of variable to a open-close parenthesis.
When posting questions here, if you have an error message from the compiler, please post the entire error message with your question. Don't paraphrase it. And indicate by obvious comment in your code, i.e., // ****** error here ***** where the error is occurring.
Anyways I was testing and while it works, it doesn't the way I want it to. I entered into the scanner "Mr. B." without the quotes of course. The program did not print the B. I'm thinking it might be the space in between Mr. and B, because other inputs with a space did the same.
Don't use Scanner#next() which gets only the next token -- the next word before reaching whitespace (here, Mr.), and will not get the rest of the text on the line. Instead use Scanner#nextLine() which gets you the whole line.
For example:
Scanner ownersname = new Scanner(System.in);
// String sownersname = ownersname.next(); // *** not this ***
String sownersname = ownersname.nextLine(); // *** but rather this ***
System.out.println(sownersname + "? That is a nice name.");
I can not release a version of my program knowing there is a GIANT glitch in the code.
Seriously, you're creating a professional application? I'm not yet at that stage, which is why I ask.
I'm wondering why, and I tried to fix it by changing ownersname.next(); to ownersname.nextLine and ownersname.next and ownersname.nextScanner and ownername.nextScanner. This is where the error comes in, when it says it can't find the variable until I change it back to it's original code, which is below.
I'd be curious to see your nextLine() method attempt, because that is the solution. Perhaps you were trying to call the method without using the method parenthesis.
I also assume that you're familiar with the Java API and have looked up the Scanner entry for it. If you did, you would see right away that there is no nextScanner() method for this class. This is one reason I have to wonder about your making a professional application at your stage. Again, I don't feel that I'm at the stage yet to create one yet, so please don't take this as an insult, just a curiosity.