Exception in thread "main" java.lang.NullPointerException
I'm going through the OCA Java SE 7 study guide and am going through packages. However, I'm inputting the same code in Eclipse, found in the book but I'm getting this error. The error is
Exception in thread "main" java.lang.NullPointerException at com.ocaj.exam.tutorial.MainClass.main(MainClass.java:12)
Here is my code...
package com.ocaj.exam.tutorial; //Package statement
//Imports class ArrayList from the java.util package
import java.util.ArrayList;
//Imports all classes from the java.io package
import java.io.*;
public class MainClass {
public static void main(String[] args) {
//Creates console from java.io package
Console console = System.console();
String planet = console.readLine("nEnter your favourite planet: ");
//Creates list for planets
ArrayList planetList = new ArrayList();
planetList.add(planet); //Adds users input into the list
planetList.add("Gliese 581 c"); //Adds a string to the list
System.out.println("nTwo cool planets: " + planetList);
}
}
Many thanks
System.console
can return null
depending on the environment in which the JVM is operating.
From the javadoc
If no console device is available then an invocation of that method will return null.
Eclipse is one of these environments where the System.console
returns null
since it typically uses javaw
which doesnt have an associated console window.
Use java.util.Scanner instead which has no such limitation.
Scanner scanner = new Scanner(System.in);
String planet = scanner.nextLine();
System.console()
will return null if the program you're running doesn't have a console associated. Try running your program in a console (a "command prompt").
That is because you are not running it directly from a system console if you are using eclipse.
To make it work replace the following code:
String planet = console.readLine("nEnter your favourite planet: ");
By:
System.out.print("nEnter your favourite planet: ");
Scanner scanner = new Scanner(System.in);
String planet = scanner.nextLine();
scanner.close();
链接地址: http://www.djcxy.com/p/84180.html
上一篇: 如何在MATLAB中模拟'包含'行为?