What causes this NullPointerException in my Java program? - java

import java.io.*;
public class listjava
{
public static void main(String args[]){
Console c = System.console();
char[] pw;
pw = c.readPassword("%s","pw: ");
for (char ch: pw)
c.format("%c ",ch);
c.format("\n");
MyUtility mu = new MyUtility();
while(true)
{
String name = c.readLine("%s","input?: ");
c.format("output : %s \n",mu.doStuff(name));
}
}
}
class MyUtility{
String doStuff (String arg1){
return " result is " + arg1;
}
}
I got an error like this:
Exception in thread "main" java.lang.NullPointerException
at listjava.main(listjava.java:7)
Why is my program wrong?

System.console() is returning null.
Quoting Java's documentation:
Returns the unique Console object associated with the current Java virtual machine, if any.
So, there are probably no console associated to your JVM. You are probably running your program within Eclipse or other IDE. Try running your program from your system's command line. It should work.
To run your program from the command line.
Go to directory where listjava.class resides
Run java's interpreter
$ java listjava

According to the Javadoc for System.console():
Returns: The system console, if any, otherwise null.
So I suppose that System.console() is handing back null and your line
pw = c.readPassword("%s","pw: ");
is therefore dereferencing null. I'm not sure what fix you might want to use; perhaps reading from System.in instead?

Related

java.lang.NullPointerException: Cannot invoke method get() on null object

I have the next Groovy code which I try to run in Jenkins Pipeline:
#Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')
import static groovyx.net.http.HttpBuilder.configure
def astros = configure {
request.uri = 'http://api.open-notify.org/astros.json'
}.get()
println "There are ${astros.number} astronauts in space right now."
astros.people.each { p->
println " - ${p.name} (${p.craft})"
}
But everytime I get java.lang.NullPointerException: Cannot invoke method get() on null object error.
When I run it from my desktop, everything works as expected:
There are 6 astronauts in space right now.
In Jenkins:
There are null astronauts in space right now.
Debug output:
<groovyx.net.http.UriBuilder$Basic#4bc2413c scheme=http port=-1 host=api.open-notify.org path=/astros.json query=[:] fragment=null userInfo=null parent=groovyx.net.http.UriBuilder$ThreadSafe#69c6847a useRawValues=null>
What should I do to make it work?
object.get() will give an NullPointerException if the object is null, so you need to check if the object is null or not before you call any method on it. so, an alternative could to check if astros != null and then call .get() within the if-block.
Handle the null issue inside your code as follows (Use null safe operator and groovy truth concept.)
#Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.3')
import static groovyx.net.http.HttpBuilder.configure
def astros = configure {
request.uri = 'http://api.open-notify.org/astros.json'
}?.get() // added null safe operator here (will handle null pointer exception)
println "There are ${astros?.number} astronauts in space right now."
//iterate if astros value exists.
if(astros){
astros.people.each { p->
println " - ${p.name} (${p.craft})"
}
}
// As you are having json, you need to parse that as follows.
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(astros)
println result
println result?.number
I take it that you created a shared library and is trying to use this in a pipeline?
I have the same problem at the moment, I think it might be a limitation of the Groovy interpreter on Jenkins, similar to how the each loop didn't work until some time ago.
I've resorted to using this version of http-builder to circumvent that for now. I'll update this if I find a proper solution (please also post an answer if you find anything).
if you facing "java.lang.nullpointerexception cannot invoke" then try to initialize every element of object_array with new class() like:
Result[] s=new Result[3];
s[0]=new Result();
s[1]=new Result();
s[2]=new Result();
Example:
class hybrid1
{
public static void main(String arg[])
{
Result[] s;
s=new Result[3];
//s[0]=new Result();
int i;
for(i=0;i<3;i++)
{
s[i]=new Result();
s[i].getroll(101);
s[i].getmarks(88.36F,78.65F);
s[i].display();
}
/*Result s1;
s1=new Result();
s1.getroll(101);
s1.getmarks(58,69);
s1.display();*/
}
}

Trying to rewrite code for an assignment to use Command-Line Arguments in Java. I have searched the existing questions

I am a new programmer in my first Java class . Here is my code but I am getting an error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0 at CmdLine.main(CmdLine.java:13)
import java.util.Scanner;
import java.util.Arrays;
public class CmdLine{
public static void main( String [] args ){
int[] array;
array = new int [ 10 ];
for(int counter = 0; counter < array.length;counter++ )
array[counter]=Integer.parseInt (args[counter]);
System.out.printf( "%s%8s\n", "Index", "Value" );
for(int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
}
}
There are many approaches to solve this.
- Methods:
I know most IDEs allow you to add command line arguments. If you are interested in this, try checking out IntelliJ and this link for further instructions:
How do you input commandline argument in IntelliJ IDEA?
There is also another way which is using a jar file,
Passing on command line arguments to runnable JAR
Basically, a Jar file works on a terminal command line like this
java -jar (type_Something)
you can write a file path or a word.
- Explanations:
When you pass in a command line arguments, the first thing you pass in is for args[0].
Ex.
java -jar Hello
Hello gets stored in args[0], and then you can use it like this:
public class Test{
public static void main(String[] args){
String argument1 = args[0];
}
}
But if you now add
java -jar Hello Friend
Hello is stored in args[0] and Friend in args[1]. Therefore, you can use it like
this:
public class Test{
public static void main(String[] args){
String argument1 = args[0];
String argument2 = args[1];
}
}
- Personal Experience:
I have used the second method, using a jar, before. I believe I had to add a Jar in my IDE before using it on terminal inside my IDE (IntelliJ). I had to send a folder path to my program, and the only way allowed was using a jar to send in command line arguments.

hasNext code in Java

I'm having trouble opening a file. The hasNext seems to crashing with the following error java.lang.NullPointer. This is my the code that's erring out (with hasNext).
import java.io.*;
import java.util.Scanner;
public class Customers{
private Scanner opener;
public void openFile() {
try {
opener = new Scanner (new File ("customer.txt"));
} catch (Exception f) {
System.out.println("Can not read file.");
}
}
public void readFile() {
while(opener.hasNext()) {
String a = opener.next();
String b = opener.next();
String c = opener.next();
System.out.printf("%s %s %s\n", a, b, c);
}
}
public void closeFile() {
opener.close();
}
}
and this is the other class:
public class fileTest {
public static void main (String args []) {
Customers c = new Customers();
c.openFile();
c.readFile();
c.closeFile();
}
}
opener might be null as there could be an exception in opening the file
public void openFile() throws Exception{
opener = new Scanner (new File ("customer.txt"));
}
If there is any exception in opening the file, then just a message is printed and opener remains null which will lead to NPE in opener.hasNext()
You should not catch the exception instead throw the exception because if you are not able to open the file, then the code should fail and the other methods should not execute.
Your question is not clear, but you seem to be saying that opener.hasNext() is throwing an NPE.
If so, that means that opener is null. That in turn means that either you are not calling openFile() OR you are calling it but it is not working. I suspect the latter, especially since the main method does call openFile().
If the openFile() method fails to open the file (e.g. because it doesn't exist with the pathname as given), then a message is printed and opener remains null. This is probably what is happening.
The openFile() method has a number of flaws:
it is catching Exception ... which could catch other exceptions than the one(s) you are expecting.
it is not logging the stacktrace or the actual exception message
it is assuming that the problem is due to not being able to open the file ... when it could possibly be something else (in general, if not in this particular case),
once it has printed the error message, it just continues as if nothing bad had happened.
The NPE problems are then a consequence of the openFile() flaws.
Note that if you print out the actual exception message, it should tell you why the application is unable to open the file.
UPDATE
The error message customer.txt (The system cannot find the file specified) is clearly telling you that it can't find the file. The chances are that your application's current directory is not the directory that contains that file. Since you used a relative pathname, you told it it look in the current directory. The solution is to either use an absolute (full) pathname ... or make sure your application is launched with the right current directory.
Once you get past this problem, there is a problem in the way that you are reading the file. The readFile() method is assuming that it is going to be able to read multiples of 3 tokens (strings) from the input. If there is a problem with the file format, you are liable to get an (unchecked) exception. You probably should catch this exception and produce a diagnostic ... rather than assuming that nothing bad can happen.
First:Make sure your file actually exists in the disk, it is possible to create a File object even if the file does not exists.
Second:You are checkin for one element by doin opener.hasNext() and accessing next 3 elements!
When there is only one element in the list opener.hasNext() return true but you are accessing next 2 elements which are not present! hence the null pointer exception
your opener is not getting initialized that why the null pointer exception, make sure the file exists there and just try to give absolute path of the file
Check few points here:
Is your program reading the file specified?If you are using eclipse,keep your file in src folder and give path as opener = new Scanner (new File ("src/customer.txt"));
2.The second problem with your code is you are only checking once for while(opener.hasNext()) for next element and then reading three elements String a = opener.next();
String b = opener.next();
String c = opener.next(); .If there is no next element in your file you will get an exception ,check for each element before accessing it.
use this code instead:
public void readFile() {
while(opener.hasNext()) {
String a = opener.next();
System.out.printf("%s\n", a);
}
}

Java error "Value of local variable is not used"

I am really new to java (started learning 2 days ago). Sorry if this is a stupid question. I am trying to learn how to use rt.exec & similar methods so I tried to make a very simple program which runs calc.exe. This is the code:
public class main {
{
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ;
}
catch(Exception exc){/*handle exception*/}
}
}
I get the error " The value of local variable p is not used".
And if I try to compile this is what I get:
I think it's easy to fix but I don't know how. Would be nice if someone helped.
Well, the error "The value of local variable p is not used.", Is not actually an error. It's your IDE (Eclipse), warning you that you aren't actually reading that variable, so you aren't receiving any input from it.
And the other problem with your class is, you don't have a main method. Like this,
public class main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ;
} catch(Exception exc){
/*handle exception*/
}
}
}
And by the way, you should always start a class name with a captial letter. So public class main, should actually be public class Main
You get that error because you don't have the main method that is used to start the java program:
public class main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ; // here, eclipse is WARINING(so you can ignore it) you that that the variable p is never used(it's just a warning)
} catch(Exception exc) {
/*handle exception*/
// never do this, always put at least a System.out.println("some error here" + e); so you don't ignore a potential exception
}
}
I believe what you have is not an error but a warning; eclipse (and other IDEs/compilers) will tell you that, although you assigned a value to the variable p, you did not use it anywhere. It tells you this because this is sometimes an error; mostly when you assign a value to a variable, you later use that variable in some way.
You can eliminate the error by changing that particular statement to just
rt.exec("calc.exe")
since you are not required to assign a value from the call to exec.
There is no such thing as a stupid qiestion(only misplaced ones, in the worst case).
The "Editor does not contain a main type" refers to the fact that you have not defined a main method. All java programs require a main method, as such:
public static void main(String [] args){
<code>
}
This is where you must place your code.
The "Value not used" is just a warning; it tells you that your variable p only exists within the try-block. You can declare your p-variable before the try - that way, you can use it outside the try-scope(the scope of a variable refers to where it exists, in this case, only inside the try-block).
If you want to use your p, this is what you're after:
public class Main {
public static void main(String[] args) {
Process p;
try {
Runtime rt = Runtime.getRuntime();
p = rt.exec("calc.exe");
} catch(Exception exc) {/*handle exception*/}
}
}
[EDIT]: Note that it is part of the java coding convention to use Capital letters for the first letter of a class, e.g. Main.java(not main.java)
The use of the variable is not in issue here. That error appears because JVM needs a method with the signature to know where to start execution.
public static void main( String args[] ){ //TODO: Stuff here }
Introduce a method with this signature in your class, and it shall clear that error.
Alternatively, you may embed your code in a static block as below - but this method is not to be recommended.
static {
// TODO: Your code here
}
Error "The value of local variable p is not used" due to the fact that nowhere in the code, you do not use the variable p.
To remove the error - it is necessary to remove the variable "p".
To run the calculator, you must use the code:
public class MainClass {
public static void main(String args[]) throws IOException {
Runtime.getRuntime().exec("cmd /c calc.exe");
}
}
This and all other comments translated by Google Translate
you are not using main how can you compile please use main method.
Ans second one is use p local variable in your method.other wise declare p variable starting of method.

Get output from a process

This is a second part to my question here.
I now have a process but I want to know how to get the output from the process?
String filename = matlab.getfileName();
Process p = Runtime.getRuntime().exec("java -cp mediaProperty.java " + filename);
My mediaProperty.java:
public class mediaProperty {
public static Object main(String[] args) {
Object[] mediaProp = null;
java.util.List lstMedia = new ArrayList();
Media media = null;
try {
media = new Media();
lstMedia.add(args);
mediaProp = media.media(3, lstMedia);
} catch (Exception p) {
System.out.println("Exception: " + p.toString());
} finally {
MWArray.disposeArray(mediaProp);
if (media != null) {
media.dispose();
}
}
return mediaProp;
}
}
The mediaProperty.java will return an Object. Inside this is actually String array. How do I get the array? And is the way I'm calling exec() correct?
use public static void main (not Object as return type)
Serialize the object using ObjectOutputStream (all necessary examples are in the javadoc)
The only thing different from the example is the construction - construct it like
ObjectOutputStream oos = new ObjectOutputStream(System.out);
in the program calling exec(), get the output with process.getOutputStream()
Read in an ObjectInputStream based on the already retreived OutputStream (check this)
Deserialize the object (see the javadoc of ObjectInputStream)
Now, this is a weird way to do it, but as I don't know exactly what you are trying to achieve, it sounds reasonable.
You could do System.setOut(new PrintStream(p.getOutputStream())) if you'd like to have the process print its results directly to standard output. Of course, this will override the old standard output. But you could also do other things with the process's output stream, like have a thread that reads from it.
A problem with your code is that the main function of a class must be of type void, and will return nothing. You will not be able to pass Java objects between processes, as they are running in different JVMs. If you must do this you could serialize the object to disk, but I imagine you don't even need to run this in a separate process.
mediaProp is a local variable in your main() method. It's not accessible from the outside.
You'll have to redesign your mediaProperty class a bit.
First, you should use:
"java -cp . mediaProperty " + filename
for calling the java process. The "-cp ." defines the classpath and I have made the assumption that the java file is compiled and the generated class file is at the same path as the executing process.
Then, you need to print the result at the standard output and not just return it. Finally, read this article for reading the output.
Tip 1: Rename the class to MediaProperty
Tip 2: Why you don't call the MediaProperty class directly from your code? Is it necessary to start a new process?
There are a few gotcha's.
In exec you assume that java is on the path, and the filename should be fully qualified or you should know that the current working dir of the java process is OK.
main() should return void (nothing). If you want to pass the results out of your program use something like:
for (Object o : mediaProp) {
System.out.println(o);
}
and parse it again on the input stream (the calling software).
Better yet, include the MediaProperty class in the java path and call main(...) directly in stead of calling a separate java process.

Categories