Scanner class in Java5 throw java.lang.NullPointerException - java

I am using scanner class in java5, and the following code will throw an exception:
Scanner scanner = new Scanner
(new File(args[0]));
int dealId;
while (scanner.hasNextLine()) {
dealId = scanner.nextInt();
System.out.println(dealId);
}
scanner.close();
The stacktrace is:
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Matcher.toMatchResult(libgcj.so.10)
at java.util.Scanner.myCoreNext(libgcj.so.10)
at java.util.Scanner.myPrepareForNext(libgcj.so.10)
at java.util.Scanner.myNextLine(libgcj.so.10)
at java.util.Scanner.hasNextLine(libgcj.so.10)
Does anybody knows what caused this exception?

The GCJ Home Page suggest it "supports most of the 1.4 libraries plus some 1.5 additions. "
Scanner was added in version 1.5 and I suspect you have hit a piece of functionality GCJ doesn't support. You need to try something different to see what you can get to work.
Is there any reason you are not using OpenJDK/Oracle Java 6 or 7? (Please don't say its for performance reasons ;)

I reproduced the error and found a work around
Here is the code, compiled on x86_64 GNU/Linux, Fedora with Java 1.5.0:
Scanner r = new Scanner(f, "ISO-8859-1");
while(r.hasNext()){
String line = r.nextLine(); //The guts of nextLine(), specifically:
//Matcher.toMatchResult bubbles up a
//nullPointerException
}
The file just contains two ascii words separated by a newline. The runtime Exception only occurs when nextLine processes the last line of the file, whether it has characters or not:
java.lang.NullPointerException
at java.util.regex.Matcher.toMatchResult(libgcj.so.10)
at java.util.Scanner.myCoreNext(libgcj.so.10)
at java.util.Scanner.myPrepareForNext(libgcj.so.10)
at java.util.Scanner.myNextLine(libgcj.so.10)
at java.util.Scanner.nextLine(libgcj.so.10)
at Main.parseFile(Main.java:1449)
at Main.construct(Main.java:1420)
at Main.populateBlogPosts(Main.java:1399)
at Main.main(Main.java:263)
Here is a bug report on this issue: https://bugs.openjdk.java.net/browse/JDK-6178785
Diagnosis
It's a bug in libgcj.so.10, perfectly legitimate ascii input as well as blankstring causes it to puke an NPE on the last line of a file.
Workaround
Since this bug only occurs on the very last line of the file, the hacky workaround is to initially make sure there is at least one newline at the end of the file, then catch and ignore the nullPointerException bubbled up from toMatchResult and exit the loop when that happens.

Related

Java repeat String with str.repeat

I have a problem with a fairly simple question in Java. To repeat a string, you can use str.repeat from Java 11. However I have the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method repeat(int) is undefined for the type String
The code is as follows:
String rep = "-";
rep = rep.repeat(4);
System.out.println(rep);
With a command-line compilation, no problem, but Eclipse is problematic, it uses
java-11-openjdk-amd64
Thanks for your help
repeat is Java 11 keyword. You are trying to use repeat from a lower version than Java 11.
modify the code with for loop as below.
String rep = "";
for(int i=0;i<4;i++) {
rep += "-";
}
System.out.println(rep);

JFlex Scanner ArrayIndexOutOfBoundsException: 769

I am trying to create a Scanner with JFlex. I created my .jflex file and it compiles and everything. The problem is that when I try to prove it, some times it gives me and error of ArrayIndexOutOfBoundsException: 769 in the .java class that JFlex created.
I am using Cup Parser generator too. I don't know if the problem can be related with the part of Cup Analysis, but here is how I called my analyzers.
ScannerLexico lexico = new ScannerLexico(new BufferedReader(new StringReader( jTextPane1.getText())));
ParserSintactico sintaxis = new ParserSintactico(lexico);
I don't know how to fix it. Please help me.
Here are the links to my code:
JFlex File "ScannerFranklin.jflex"
Java Class generated "ScannerLexico.java"
The part where I have the problem in the .java class created by JFlex, in next_token() function (Line 899 in java file).
int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
if (zzNext == -1) break zzForAction;
zzState = zzNext;
Thanks.
According to its documentation, JFlex throws ArrayIndexOutOfBounds exceptions whenever it encounters Unicode characters using the %7bit or %8bit/%full encoding options. It recommends to always use the %unicode option instead, which is the default.
You are using the %unicode option, but you're also using %full. Apparently when you have both options, %full takes precedence. So remove %full and the error should go away.

ArrayIndexOutOfBoundsException when using XStream

I'm not sure how this is even possible, but the program I am running is giving me an odd error. I am getting an ArrayIndexOutOfBoundsException: -1 on a for each loop. The entire error is below:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at com.thoughtworks.xstream.core.util.OrderRetainingMap.entrySet(OrderRetainingMap.java:77)
at java.util.HashMap.putMapEntries(HashMap.java:511)
at java.util.HashMap.putAll(HashMap.java:784)
at com.thoughtworks.xstream.core.util.OrderRetainingMap.<init>(OrderRetainingMap.java:36)
at com.thoughtworks.xstream.converters.reflection.FieldDictionary.buildMap(FieldDictionary.java:135)
at com.thoughtworks.xstream.converters.reflection.FieldDictionary.fieldsFor(FieldDictionary.java:76)
at com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider.visitSerializableFields(PureJavaReflectionProvider.java:126)
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doMarshal(AbstractReflectionConverter.java:81)
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.marshal(AbstractReflectionConverter.java:72)
at com.thoughtworks.xstream.core.AbstractReferenceMarshaller.convert(AbstractReferenceMarshaller.java:69)
at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:58)
at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:43)
at com.thoughtworks.xstream.core.TreeMarshaller.start(TreeMarshaller.java:82)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.marshal(AbstractTreeMarshallingStrategy.java:37)
at com.thoughtworks.xstream.XStream.marshal(XStream.java:895)
at com.thoughtworks.xstream.XStream.marshal(XStream.java:884)
at com.thoughtworks.xstream.XStream.toXML(XStream.java:857)
at com.thoughtworks.xstream.XStream.toXML(XStream.java:844)
at unl.cse.assignments.DataConverter.output(DataConverter.java:210)
at unl.cse.assignments.DataConverter.main(DataConverter.java:121)
Line 210 is the pw.print line:
for(Product p : products)
{
if(AwardTicket.class.isInstance(p)){
xstream.alias("awardTicket", AwardTicket.class);
pw.print(xstream.toXML(p) + "\n");
}
}
(Line 121 just calls on the output)
I've been investigating this error for a long time and I can't figure out the cause of it. I assumed there was something wrong with the xstream, but I tried it with other outputs.
As Andreas pointed out, this is actually a bug in XStream that was fixed in version 1.4.6. The latest version of XStream can be downloaded here.

NullPointerException on return new[]

I have a very strange problem with NullPointerException. Code example is as follows:
...
... public String[] getParams(...) {
... ...
... ...
143 return new String[] {
144 getUserFullName(),
145 StringUtil.formatDate(sent),
. tiltu,
. StringUtil.initCap(user.getName()),
. vuosi.toString(),
. asiatyyppi[0] + " " + lisatiedot[0],
. asiatyyppi[1] + " " + lisatiedot[1],
. alaviitteet[0],
152 alaviitteet[1]};
153 }
Now, I have got an issue from production having a stack trace:
java.lang.NullPointerException
at package.EmailService.getParams(EmailService.java:143)
...
I am unable to produce that kind of stack trace myself. It maybe some environment issue that for some reason line numbers don't match. If I have null references on any variable stack trace points to that specific line but never to line 143.
But what I want to ask is: is it possible to produce NullPointerException at line 143 specifically?
The line number in the stack trace comes from the LineNumberTable attribute in the class file. (See JVM specification)
It would be no problem to output the right line number for a subexpression - all the compiler has to do is to say that from byte-code index x to y, there is a correspondence with source code line z.
But up to and including Java 1.7 there was a bug in the compiler, that was fixed in 1.8:
https://bugs.openjdk.java.net/browse/JDK-7024096
A DESCRIPTION OF THE PROBLEM : linenumbertable in compiled code only
has line numbers for starts of statements. When a statement is using
method chaining or other "fluent Interface" style API's a single
statement can span tens of lines and contain hundreds on method
invocations.
Currently an exception throw from within any of these methods will
have the linenumber of the first line of the enclosing statement which
makes it very hard to debug which method call is having a problem.
linnumbertable should have correct line numbers for every method
invocation.
--
BT2:EVALUATION
It seems simple enough to fix this, but its kinda risky at the end of
the jdk7 development cycle, targetting to jdk8.
So in 1.7, you would get the wrong reported line number for these kind of subexpressions (if they occurred within the same method though - if you invoked another method in a subexpression, and that other method caused a NullPointerException, you would see it reported there - this is probably why the bug isn't always a big problem)
One way you could work around this is by taking the Java 8 compiler to compile your source code, and use the flags javac -source 1.7 -target 1.7. But it would be better and safer to upgrade your prod environment to 1.8.
Consider your original code which defines a new String array:
return new String[] {
getUserFullName(),
StringUtil.formatDate(sent),
tiltu,
StringUtil.initCap(user.getName()),
vuosi.toString(),
asiatyyppi[0] + " " + lisatiedot[0],
asiatyyppi[1] + " " + lisatiedot[1],
alaviitteet[0],
alaviitteet[1]};
}
If any of the elements of the inline array should trigger a NullPointerException the JVM will interpret the Exception as having occurred on the line where the definition began. In other words, the JVM will view the above code as being the same as:
return new String[] { getUserFullName(), StringUtil.formatDate(sent), tiltu, StringUtil.initCap user.getName()), vuosi.toString(), asiatyyppi[0] + " " + lisatiedot[0], asiatyyppi[1] + " " + lisatiedot[1], alaviitteet[0], alaviitteet[1]}; }
where everything is on one line.
If you really want to handle NullPointerExceptions here, you should define the variables outside the instantiaition.

Java : The constructor JSONTokener(InputStreamReader) is undefined

I have a quite strange issue with Java, I'm getting an error on some machines only, I would like to know if there is any way I can avoid that:
This is the line of code concerned:
JSONTokener jsonTokener = new JSONTokener(
new InputStreamReader(is, "UTF-8"));
This is the error I get on some machines
The file *.java could not be compiled. Error raised is : The constructor JSONTokener(InputStreamReader) is undefined
Check the classpath on the machines where this error occurs. This could happen because the library that contains the JSONTokener class is from an older version, where only the JSONTokener(String) is available, and not JSONTokener(Reader).

Categories

Resources