Unable to execute Java code in SciTE - java

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).

Related

Message appears after writing an input in java

I'm new to Java and i was learning inputs with Scanner but i'm getting something odd, the message of "enter a number" doesn't show, it only appears after I enter a value, here is the code and the screenshot. I'm using java 11 btw.
`
public class HolaMundoMain {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int numero;
System.out.print("Enter a number: ");
numero = entrada.nextInt();
System.out.println("The number is: "+numero);
}
}
`
I tried writing the sout line before declaring Scanner but it does not work
I was expecting that first it would appear "Enter a number: " and then i could write it, but i have to write it first and then the message appears
see image of terminal
The code it's working on my end. Try to compile it using javac HolaMundoMain.java and run with java -cp . HolaMundoMain.
Image of the code running
The code is perfectly fine, i tried running it as well and it does print first "Enter a number :" then after you enter value, it prints the next sout statement along with the value., the image shows my run of the said code. Have you made any changes to java code? It's possible that you wrote the statement that takes input first then sout then you compiled it and ran it for the first time, but after changing it you forgot to compile it again using "javac completeFileName" in CMD. I have a strong feeling you just need to recompile it and then run the program using "java completeFileName". Also please note that, completeFileName is a name of path of file. if you don't compile after making changes to a file, what happens is compiler runs the previously compiled version of it, which is basically a fileName.class file(you can even see it in folder), but when you do compile again a new fileName.class is created and then used to run.

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.

NullPointerException in Eclipse but not in command promt

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);

NoSuchElementException when using do while loop

I'm working on my College project and I keep getting this exception when I try to make all my code loop. When not in a loop it works perfectly fine, it includes creating text files and appending text files (if thats any help). My assumption is that my scanner is causing these problems, but I don't know what the problem is or how to fix it.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at PDispenser_V1.main(PDispenser_V1.java:51)
I can't post my code because plagiarism software checks stackoverflow and my full project will be plagiarised if I do. I know that's a huge downfall but if you could tell me what to look for in general and how to fix it (provided I gave you enough to go on) that would be great! Also the only line number the complier gave me that exists is 51 and it has this code on it.
selection = input.nextInt();
This line is followed by a switch statement with a bunch of methods in each case. If theres anything I can answer without showing any code please ask. Any help is appreciated.
EDIT: I should also say, it complies fine but when I go to select one of the options again thats when it throws the exception.
EDIT2: I should also mention that the selection is taking a line from the user not a file.
You are probably using nextInt without checking if there is one available to read on the stream, as the javadoc for nextInt says:
Throws:
NoSuchElementException - if input is exhausted
Try using hasNextInt() to check if there is an int before attempting to read one from the stream.
Exception is throwing because, there is no next token for the input to return.
To avoid such exceptions it is always best practice to first check the existence of next token using input.hasNextInt() . If it returns true then extract the next token using input.nextInt(). Example.
if (input.hasNextInt())
{
int i = input.nextInt();
}
EDIT
This Error can be produced in following way:
public class Scanned
{
public static void main(String st[])
{
Scanner input = null;
try
{
InputStream in = System.in;
input = new Scanner (in);
while (true)
{
System.out.println(input.nextInt());
in.close();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
Make sure that the InputStream is not closed within the loop.

Program output lost when passed through PsExec

(This is a question my coworker posted elsewhere, but I thought I'd post it here to see if I could hit a different audience.)
Hello all,
I'm testing the possibility of writing a small java application the will use Psexec to kick off remote jobs. In the course of testing binding the stdin and stdout of a java program to psexec I came across an odd bug.
My test program is a basic echo program. It starts a thread to read from stdin and then pipes the read output directly back to stdout. When run on the local machine, not from psexec, it works beautifully. Exactly as it should.
However, when I call it from PsExec the first time the input is piped directly into stdout it is lost. What makes the bug really bizzare is that it is only the first time the input is piped directly into stdout that it is lost. If the input String is appended to another string it works fine. Either a String literal or a String variable. However, if the input String is sent directly to stdout it doesn't go through. The second time it is sent to stdout it goes through fine - and everytime there after.
I'm at a complete loss as to what's going on here. I've tried to test for every possible bug I can think of. I'm out of ideas. Did I miss one or is this just something inside psexec?
Here is the code in question, it's in three classes (one of which implements an interface which is a single function interace).
The Main class:
public class Main {
public static void main(String[] args) {
System.out.println("Starting up.");
CReader input = new CReader(new BufferedReader(
new InputStreamReader(System.in)));
CEcho echo = new CEcho();
input.addInputStreamListener(echo);
input.start();
System.out.println("Successfully started up. Awaiting input.");
}
}
The CReader class which is the thread that reads from stdin:
public class CReader extends Thread {
private ArrayList<InputStreamListener> listeners =
new ArrayList<InputStreamListener>();
private boolean exit = false;
private Reader in;
public CReader(Reader in) {
this.in = in;
}
public void addInputStreamListener(InputStreamListener listener) {
listeners.add(listener);
}
public void fireInputRecieved(String input) {
if(input.equals("quit"))
exit = true;
System.out.println("Input string has made it to fireInputRecieved: "
+ input);
for(int index = 0; index < listeners.size(); index++)
listeners.get(index).inputRecieved(input);
}
#Override
public void run() {
StringBuilder sb = new StringBuilder();
int current = 0, last = 0;
while (!exit) {
try {
current = in.read();
}
catch (IOException e) {
System.out.println("Encountered IOException.");
}
if (current == -1) {
break;
}
else if (current == (int) '\r') {
if(sb.toString().length() == 0) {
// Extra \r, don't return empty string.
continue;
}
fireInputRecieved(new String(sb.toString()));
sb = new StringBuilder();
}
else if(current == (int) '\n') {
if(sb.toString().length() == 0) {
// Extra \n, don't return empty string.
continue;
}
fireInputRecieved(new String(sb.toString()));
sb = new StringBuilder();
}
else {
System.out.println("Recieved character: " + (char)current);
sb.append((char) current);
last = current;
}
}
}
}
The CEcho class, which is the class that pipes it back to stdout:
public class CEcho implements InputStreamListener {
public void inputRecieved(String input) {
System.out.println("\n\nSTART INPUT RECIEVED");
System.out.println("The input that has been recieved is: "+input);
System.out.println("It is a String, that has been copied from a " +
"StringBuilder's toString().");
System.out.println("Outputting it cleanly to standard out: ");
System.out.println(input);
System.out.println("Outputting it cleanly to standard out again: ");
System.out.println(input);
System.out.println("Finished example outputs of input: "+input);
System.out.println("END INPUT RECIEVED\n\n");
}
}
And finally, here is the program output:
>psexec \\remotecomputer "C:\Program Files\Java\jre1.6.0_05\bin\java.exe" -jar "C:\Documents and Settings\testProram.jar"
PsExec v1.96 - Execute processes remotely
Copyright (C) 2001-2009 Mark Russinovich
Sysinternals - www.sysinternals.com
Starting up.
Successfully started up. Awaiting input.
Test
Recieved character: T
Recieved character: e
Recieved character: s
Recieved character: t
Input string has made it to fireInputRecieved: Test
START INPUT RECIEVED
The input that has been recieved is: Test
It is a String, that has been copied from a StringBuilder's toString().
Outputting it cleanly to standard out:
Outputting it cleanly to standard out again:
Test
Finished example outputs of input: Test
END INPUT RECIEVED
have you tried redirecting the output into a file ( java... >c:\output.txt )? this way you could doublecheck if everything is going into stdout and maybe just getting eaten by psexec
PsExec is eating the output. Next interesting thing might be where it's eating the output. You could check this by getting a copy of Wireshark and checking whether the output in question is traversing the network or not. If it's not, then it's being eaten on the remote side. If it is, it's being eaten locally.
Not that I'm really sure where to go from there, but collecting more information certainly seems like a good path to be following...
I was having the same issue and tried multiple combinations of redirects.
This is what worked:
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.redirectInput(Redirect.INHERIT);
final Process process = processBuilder.start();
// Using Apache Commons IOUtils to get output in String
StringWriter writer = new StringWriter();
IOUtils.copy(process.getInputStream(), writer, StandardCharsets.UTF_8);
String result = writer.toString();
logger.info(result);
final int exitStatus = process.waitFor();
The Redirect.INHERIT for processBuilder.redirectInput got me the missing remote command output.
Is System.out not configured for autoflush? After the first print try System.out.flush() and see if the first line appears without more lines being printed.
(oh yeah, seriously, it is "RECEIVED", not "RECIEVED".)
OK, I've been thinking about this over the weekend and I since you are jumping from machine to machine I wonder if maybe there is a CharSet issue? Maybe it is eating the string the first time and dealing with a different code page or character set issue? Java is 16bit characters normally and windows is either 8bit with code pages or utf-8 these days.
Any chance the local and remote machines have different default character sets? If you are sending localized data over the net it might misbehave.
What I see when running psexec is that it spawns a child window to do the work but doesnt return that program's output to it's console window. I would suggest using WMI or some form of windows process API framework to gain a level of control you appear to lack with psexec. Surely java has an equivalent to .Net's System.Diagnotics.Process class.
Maybe you could try passing a copy of input to your listeners:
public void fireInputRecieved(String input) {
if(input.equals("quit"))
exit = true;
String inputCopy = new String(input);
System.out.println("Input string has made it to fireInputRecieved: "
+ input);
for(int index = 0; index < listeners.size(); index++)
listeners.get(index).inputRecieved(inputCopy);
}
I had similar problems with listeners where a passed variable would end up empty unless I did pass an explicit copy of it.
I don't necessarily have an answer, but some comments may prove helpful.
The "pass a copy" idea shouldn't matter, since your output successfully prints the string twice before the failure, then succeeds again afterward.
auto-flush shouldn't matter either, as you've already mentioned
Niko's suggestion has some merit, for diagnostic purposes. Mixed with Mark's suggestion, it makes me wonder if there aren't some invisible control characters getting involved somewhere. What if you printed the characters byte values as a diagnostic step?
You know that the value is "Test" (at least in the output you gave us). What happens if you pass "Test" directly to the failing printLn statement?
In situations like this, you want to gain as much information as possible. Insert breakpoints and analyze characters. Send the bytes to files and open them in hex editors. Do whatever you can to trace things as accurately and as precisely as possible.
Come up with weird test scenarios and try them, even if they shouldn't possibly help. You never know what good idea you might have while analyzing the results of the hopeless idea.
I'd guess that there is a bogus byte in there prefacing the T. According to JavaDocs, an InputStreamReader will read one or more bytes, and decode them into characters.
You could have an escape sequence or spurious byte in there, masquerading as a multibyte character.
Quick check - see if "current" is ever > 128 or < 33.
What if you used a CharArrayReader to get individual bytes, without any charset translation?
The theory is that during the first attempt to output the String using println, it's sending an escape character of some sort, eating the rest of the string. During later prints, either Java or the network pipe are handling or removing it, since it previously got that escape sequence, perhaps changing the handling in some way.
As an unrelated nit, sb.toString() returns a new String, so it's unnecessary to call "new String(sb.toString())"
Same issue here, I'm going through this post again and again these days, hoping I can find some solution. Then I decide I should give up psexec and find some alternative. So this is the thing: PAExec. Works perfect for getting command output.
How are you executing PsExec? My suspicion is that this is some code within PsExec which is actually doing echo suppression, possibly for the purposes of protecting a password. One way to test this hypothesis would be to change this code:
System.out.println("Outputting it cleanly to standard out: ");
System.out.println(input);
System.out.println("Outputting it cleanly to standard out again: ");
System.out.println(input);
to this:
System.out.println("Outputting it cleanly to standard out: ");
System.out.print(' ');
System.out.println(input);
System.out.println("Outputting it cleanly to standard out again: ");
System.out.println(input);
...thereby causing the output to be (if I'm right):
Outputting it cleanly to standard out:
Test
Outputting it cleanly to standard out again:
Test
Finished example outputs of input: Test
In particular, it's noticeable that the apparently-suppressed line is the first line which consists solely of Test - which is exactly the text you've just sent to the remote system. This sounds like PsExec attempting to suppress a remote system which is echoing its input in addition to producing its own output.
Is the password of the user on the remote machine perhaps Test? Are you using PsExec's -p parameter? Are you specifying -i?
I am dealing with this same issue and I am wondering if it has to do with how the cmd window and pipes in windows work while you don't have a true windowed session. The suppressed output happens when any new process is spawned. You would think that if you spawn a process that the stdout/stderr/stdin would be inherited from the process that spawned it; after all that is what happens if you spawn the process from a normal cmd window and the output from the new process is piped back to your own console. However if somewhere in the inheritance of the pipes something were to go wrong, like say not passing a WINDOW.GUI object because there is no physical window, windows doesn't let the stdin/stdout/stdin to be inherited. Can any one do some investigation or open a windows support ticket for this?
Seems no easy solution. My work-around in a recent project is using paexec.exe product. It captures output/error easily in JAVA(java-8), but hangs up upon completion of the remote command execution. When running this inside a server on the hosted machine, I have to spurn a new child JVM process to run paexec.exe and force kill it via its PID upon completion in order to release all the resources.
If anyone has better solution, please post it.

Categories