NullPointerException in Eclipse but not in command promt - java

I'm a beginner. Just wondering why this code works perfectly fine in windows command prompt, but I get an:
Exception in thread "main" java.lang.NullPointerException
at Test1.main(Test1.java:13)
error in eclipse. This has happened a lot to me, and it's really stopping me from using eclipse.
Here's the code:
import java.io.Console;
public class Test1 {
public static void main(String[] args) {
Console myConsole = System.console();
for (int a = 0; a < 10; a++){
int a2 = a * a;
myConsole.printf("\n%d squared is: %d.",a,a2); //Problem with this line
}
System.exit(0);
}
}

The javadoc for System.console() states
Returns The system console, if any, otherwise null.
Eclipse must not associate a system console.
Use System.in instead, possibly with a java.util.Scanner for input. And System.out for output.

Simply put, System.console() is returning null in Eclipse, but not when run in a console. This is the documented behaviour:
Returns the unique Console object associated with the current Java virtual machine, if any.
Returns:
The system console, if any, otherwise null.
Why not just use System.out instead? After all, you don't need any of the functionality of Console.

System#console may return null in certain environments. Since youre simply outputting to the console, you don't need to use Console. Formatter can be used instead:
System.out.printf("\n%d squared is: %d.", a, a2);

Related

Looping a .next() in a while() loop gives NoSuchElementException in one compiler but not on another

I am a novice at coding but cannot understand why it runs fine on my machine, but when I upload my code I get a "NoSuchElementException" on line 19, "String command = keyboar.next();" I understand it has to do something with closing the scanner but I cannot figure out any other way to work it so it loops the print screen and input. Especially since it works fine when I run it on my machine.
Any insight is much appreciated here
import java.util.Scanner;
public class example1
{
public static void main(String[] args)
{
System.out.println("Enter an ending value");
Scanner keyboard = new Scanner(System.in);
int input;
input = keyboard.nextInt();
while(true){
System.out.println("Count up or down?");
String command = keyboard.next();
if (command.equalsIgnoreCase("up")) {
int one = 1;
int ten = 11;
int hund = 101;
while (one <= input) {
System.out.printf("%5d %4d %4d\n", one, ten, hund);
one++;
ten++;
hund++;
}
}
if (command.equalsIgnoreCase("down")) {
int neg = -input;
int one = -1;
int ten = 9;
int hund = 99;
while (one >= neg) {
System.out.printf("%5d %4d %4d\n", one, ten, hund);
one--;
ten--;
hund--;
}
}
}
}
}
You've created a scanner that reads from System.in. You don't close it anywhere, so I'm not sure why you wrote in your question that you feel it has something to do with that.
System.in does not represent the keyboard. It represents the java process's 'standard in' stream. If you just run java -jar foo.jar or whatnot on the command line (which is its own process, called the 'shell' - it'll be cmd.exe on windows, perhaps /bin/bash on linux. It's just an application, nothing special) - then that shell will decide that you intended to hook up the keyboard (technically, the 'terminal', which is usually virtualized, for example if you use ssh or other tools to remote your way onto another server, usually a physical keyboard isn't even connected to those things!).
But that's just because you started that process in a command line without explicitly specifying. If you double-click a jar on linux you probably won't get any terminal and nothing will be hooked up to standard in. If instead you start java -jar yourapp.jar <somefile.txt then bash will open the somefile.txt and set that up as the standard in.
The keyboard never runs out - you won't get a NoSuchElementException there.
But files run out. Given that you get this error when you 'upload' your application, clearly, something has been hooked up when whatever you uploaded it to runs your application that isn't the keyboard. It's probably a file, or at any rate, a limited stream.
You're asking for more tokens when there is nothing left to give.
Here's one obvious explanation:
This is homework or some coding exercise / coding competition.
You are uploading it to a grading server or competition testing server.
That server is (obviously - or you'd have to hire folks to type input data in over and over!) running your java app with the test data hooked up to System.in, and not an actual keyboard or even a virtualized one. Nobody is entering any keys to toss the test data at your app.
You have misunderstood the format of what the input is, so your application attempts to read more tokens than there actually are.
You can trivially reproduce this error yourself. First make a text file named 'test.txt', containing the string Hello and nothing more:
> cat test.txt
Hello
> cat Test.java
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(in.next());
System.out.println(in.next());
}
}
> javac Test.java
> java Test <test.txt
NoSuchElementException
After all, this code tries to read 2 tokens from the standard input, which is that test file, which doesn't have 2 tokens. The same thing is happening in your setup.
SOLUTION: Reread the exercise description, you've misunderstood the inputs. For example, I bet the description says that a blank line means you need to exit the app, or if a command quit or exit comes in, or whatnot. Your app runs forever, it's highly unlikely homework / a coding exercise requires this.

Unable to execute Java code in SciTE

I have written a sample code:
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
String b = a.next();
System.out.println(b);
}
}
I am able to compile and execute this code via Ubuntu terminal. In SciTe, it compiles fine, but when I run it, I am faced with this error:
please enter a: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at abcd.main(abcd.java:8)
Any Suggestions?
EDIT: When I execute a file in terminal, I do: 'java abcd' Scite does: 'java -cp .abcd'. How are the two commands different and why isn't java -cp working?
It appears that there is a bug/improper implementation in the handling of standard input in SciTE on Linux/Unix.
The description of the bug and a workaround are in this PDF document: A Problem with SciTE Go Command on Linux
Note: this is not official documentation, but it seems to match your problem.
According to that document, when running a Java program through the "Go" command on SciTE, input is supposed to come from the output pane. However, on Linux this does not work properly, and it's as if you are reading from an empty stream.
When you are reading from an empty stream, Scanner sees the end-of-file marker when it attempts to read a value using next(), nextInt() etc. And it throws a NoSuchElementException as there is no input element in the stream.
Your options to work around this problem:
Try the method mentioned in the aforesaid document, to use "Go" in a Linux terminal instead of the output pane.
Run the program in a terminal and avoud the "Go" command altogether.
Use a different IDE which doesn't have this problem.
Try to use hasNext() before next();
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
while(a.hasNext()) {
try {
String b = a.next();
System.out.println(b);
} catch (NoSuchElementException e) {}
}
}
}
I don't mean to offend, but using hasNext() as suggested in Alexander's answer won't solve this problem, it will only enable OP to handle it well. I don't think that is what he/she is looking for.
Now I am no expert by any means and for some reason your program code works on my machine... But anyways, a NoSuchElementException is thrown when your program is cycling over an iterable object and there is nothing more to cycle over, despite your program expecting something there. A quick look-up in the Java-docs of Scanner.next()
shows that this exception is thrown if there are no more tokens available for read.
Now, if I had to guess I would advise you to try using something other than Scanner.next() and see if that works.
The fact that it works on my machine but not on yours is somewhat surprising, so could you provide some information on how you try to run your program? Are you running it from the default command-line? Or within Scite? (If second is the case, I really won't be able to help you, I have never even touched Scite).

User Input Java

I am building an application in Java (using NetBeans) that accepts user input through the console and prints out a statement using their name (given in user input). The following is the code:
package amazingpets;
import java.io.Console;
public class AmazingPets {
public static void main(String[] args) {
Console console = System.console();
String firstName = console.readLine("What is your name? ");
console.printf("My name is %s.\n",firstName);
}
}
However I keep getting the following error in the console:
Exception in thread "main" java.lang.NullPointerException
at amazingpets.AmazingPets.main(AmazingPets.java:14)
Java Result: 1
Can anyone please suggest a possible solution?
From the documentation of System#console, it returns:
The system console, if any, otherwise null.
So your code is equivalent to:
String firstName = null.readLine("What is your name? ");
I would suggest you to use Scanner scanner = new Scanner(System.in); instead.
System.console() returns a console if it exists. Java apps may be launched without a console.
Anywhy it seams this is a duplicate of this one (among others):
Why does System.console() return null for a command line app?
Hope it helps
Use Scanner instead of Console
As mentioned in this answer this answer
Isn't line 14 where you create firstName variable? In this case console may be null. Javadoc for Console says
` a unique instance of this class which can be obtained by invoking theSystem.console() method. If no console device is available then an invocation of that method will return null.`
When you run code in an IDE you will usually not have a console object. System.console() will thus return null and console.readLine("What is your name? "); will generate a NullPointerException. You can still read via System.in, so to read a line you can instead use:
Scanner sc = new Scanner(System.in);
String read = sc.nextLine();

Console class in java Exception in reading password

i am trying to use Console class in java. with this code
import java.io.Console;
public class ConsoleClass {
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;
}
}
here i am getting NullPointerException when i tried to run in netbeans but i am not getting any Exception when tried to run in cmd with out netbeans IDE.Why?
static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.
If any.
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
Consoles are typically associated with processes that run independently of frameworks. They are a means of interfacing a process's standard input and output with a shell. If your classes are running as a component of a larger framework, the framework may own the console, and your program might not have a console at all.
There are other conditions and techniques to launch a program without a console. They are typically used when the destruction of the console is guaranteed to occur, but you want the program detached in such a manner that the console's destruction doesn't signal the program's termination.
As such, you cannot guarantee the existence of a console; but, if you are going to run your program in an environment where the console is likely to be present, you should take advantage of it.
System.console() returns a Console instance if a console is associated with the process. - Running under NetBeans you likely don't have an associated console.

Java console API

I tried the java.io.Console API using eclipse. My sample code follows.
package app;
import java.io.Console;
public class MainClass {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Console console = System.console();
console.printf("Hello, world!!");
}
}
When I tried running the example, I got the following error.
Exception in thread "main"
java.lang.NullPointerException at
app.MainClass.main(MainClass.java:11)
Where did I go wrong? Thanks.
Since you've mentioned in a comment that you're using Eclipse, it appears that there is currently no support for Console in Eclipse, according to this bug report.
The System.console method returns a console associated with the current Java virtual machine, and if there is no console, then it will return null. From the documentation of the System.console method:
Returns the unique Console object associated with the current Java
virtual machine, if any.
Returns:
The system console, if any, otherwise null.
Unfortunately, this the correct behavior. There is no error in your code. The only improvement that can be made is to perform a null check on the Console object to see if something has been returned or not; this will prevent a NullPointerException by trying to use the non-existent Console object.
For example:
Console c = System.console();
if (c == null) {
System.out.println("No console available");
} else {
// Use the returned Console.
}
System.console returns null if you don't run the application in a console. See this question for suggestions.
System.console returns the unique Console object
associated with the current Java
virtual machine, if any.
you have to test if console is null before using it.

Categories