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()];
Related
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
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.
I have a .txt file that is formatted as follows
The Shawshank Redemption
100
19.95
DVD
There are many more lines, but I'm trying to store these values into four different ArrayLists. The problem is a get the error java.util.InputMismatchException. Here is my code:
while(list.hasNext() && !list.nextLine().equals("")){
titleList.add(list.nextLine());
quantityList.add(list.nextInt());
priceList.add(list.nextDouble());
typeList.add(list.nextLine());
}
The program crashes at quantityList.add(list.nextInt()); telling me that the next line is not and int, giving me that error. It will read it though if I use nextLine(). Any tips anyone can give me would be extremely helpful.
You have already read the first line in your while statement: -
while(list.hasNext() && !list.nextLine().equals(""))
And then when you again call nextLine first time, you are actually reading the integer (100), using list.nextLine and that is why you get that exception. Because you are probably now storing a String in an Integer List. Just remove that 2nd test from while.
2nd problem is that, you have checked list.hasNext() just once, and then you are reading 4 inputs. That may again throw you exception, if you go out of input. So, you also need to take care of that.
And another issue, which you will get is due to the usage of list.nextInt() and list.nextDouble(). Remember that, those methods read the input till the newline character at the end. So, the newline character left after reading will be read by the following invocation of method reading input, if not consumed. So, you also need to add an empty list.next() call after both of those methods, to consume the newline, so that newline is not read by list.nextDouble() used after list.nextInt(), else you will keep on getting exception.
Apart from those problems, I would suggest you to create a Class storing those attributes, and the have a List of objects of that class, rather than having 4 different lists.
Say I am importing a file, which contains lines. I would like to reverse this file by recursively outputting the tail of sequence, followed by the head of the sequence. Is this possible using a BufferedReader? Or would I first need to import these lines into a list? I have to do it with recursion.
So for example, I have a file containing the following:
Hi
My
Name
Is
Mark
I would like it to output in reverse order in another file:
Mark
Is
Name
My
Hi
I think I have created the recursive method correctly, although it compiles fine, but the output file is empty after the program is run.
public void Reverse(BufferedReader br, PrintWriter pw) {
try {
String headLine = br.readLine();
if (headLine != null) {
Reverse(br, pw);
pw.println(br.readLine());
}
pw.println(headLine);
} //try
It has to be using recursion
Here is a recursive solution:
read one line from the file;
recursively reverse the remainder of the file;
write out the line read in step 1.
Since this is homework, I leave it to you to figure out how to translate this into actual Java code.
Instead of outright giving you the solution, you probably don't want to think of this in terms of head and tail. Think of it in terms of lines and then read the answers and discussions to this SO question. You can apply the same technique.
By all means read everything into a LinkedList and then throw recursion on it. Only, Collection Framework is a very cumbersome match for this kind of work.
I have a strange problem which I can't fix:
A field:
private boolean[][][] gaps;
Constructor (1st line):
gaps = new boolean[NOBARRICADES][WIDTH][HEIGHT];
Constructor (2nd line):
for (int i = 0; i < NOBARRICADES; i++) {
Java throws an error for the 2nd line, saying:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
Does it have anything to do with Java syntax (the mistake is in these lines of code) or I should look for the problem somewhere else?
You're probably misreading the error output. Your second line does not even access the array - make sure that it's not the first line of the body of the for-loop that throws the exception. Also, make sure that you use i only to index the first dimension of your array.
sometimes the java compiler is off by a line or two. You may check the lines of code around the line that it says the error is on and see if you see anything.
Sorry, but you really don't want to do that.
Multidimensional arrays are never worth the confusion they cause--they have no positive value at all (with the POSSIBLE exception of a clear, obvious x,y array).
I suggest you try starting with either a list of two-dimensional arrays or a two-dimensional array of objects where each object contains a list.