Intellij idea input - java

import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.next();
int x=sc.nextInt();
System.out.printf("%-15s%03d\n", s1, x);
}
System.out.println("================================");
}
}
here is a input:
java 10
cpp 65
python 50
the output is this,
java 010
cpp 065
python 050
When I run the program and copy the input to console,there is two case.
when the cursor is after 50 and i copy this whole input the program prints first two lines of ouput and waits for me to push the enter button.Then it gives the third line of output.
But when the cursor is in the 4th line meaning under line of python 50 and i copy this whole input to console, the program works fine.But i don't have to push enter to finish the input.It automatically gives correct output.
In both the cases, netbeans works fine.But i have to push enter after copying input to console to which is normal for any input.
what is the problem here?

netbeans may be automatically inserting a linebreak or whitespace when you press enter, where as intelliJ may be stripping the final one, and treating it as 'send to terminal'
There is no problem, just different terminals acting differently.

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.

nextLine() and while loop misbehavior in unicode-16

Edit: This actually turned into quite an interesting problem. After some help from commenters, I posted a self-answer. I should mention that my project is in Unicode-16, which looks like it was the source of the trouble.
The problem is that the loop was not exiting as expected, in what appears to be trivially simple code:
import java.util.Scanner;
public class Lambda2 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String input = in.nextLine();
while (!input.equals("exit")){
System.out.println("input is \""+ input + "\"");
System.out.println(input.equals("exit"));
input = in.nextLine();
}
System.out.println("Thank you!");
}
}
Run 1:
exit
Thank you!
So far, so good. But when I enter the loop, I run into trouble:
Run 2:
asdf
input is "asdf"
false
exit
input is "exit"
false
exit
input is "exit"
false
Last I checked "exit".equals("exit") should return true, not false. I've tried using trim() on my inputs in case there was some skullduggery with new lines... What in the world am I missing??
Neither of them posted an answer, but with the help of GBlodgett and StephenC, an interesting answer did eventually emerge.
The problem was that the project is, by necessity, in a UTF encoding, and a BOM character (U-FEFF) was being added to the beginning of the user input, making it 5 characters long.
The solution was to remove the BOM character immediately after collection:
input = input.replace("\uFEFF", "");
What is still somewhat mysterious, however, is why no BOM was added to the first input, but only to the subsequent ones. It seems like Run 1 should not have worked.
I tried this code and it is working fine.

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

Weird System.out.print Behavior in Netbeans

I'm getting weird results from the System.out.print immediately below the Scanner declaration in the code snippet below. It seems like it's executing twice. I've debugged it and immediately after executing the print statement I get this in standard out:
run:
Input a freaking binary number: Input a freaking binary number:
I added the "freaking" to verify it wasn't somehow entering the while loop print without me knowing.
For your info this is being executed in the netbeans IDE 6.7.1 on a 64 bit vista machine with the 64 bit JDK. Hopefully you can see the error of my ways!
Thanks!
Edit: When executing the Netbeans generated JAR file on the command line the statement only prints once. Has anyone encountered this kind of weird behavior in Netbeans that might know how I can prevent this from happening. I hate having to work outside my IDE during development cycles.
private void getInput()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Input a freaking binary number: ");
// Grab the next inputed long and save it in the currentValueInBinary
// member variable
setCurrentValueInBinary(scanner.nextLong());
// Loop until a valid binary number is retrieved
while (!isNumberBinary(currentValueInBinary))
{ // Input was negative, report error and re-request input
System.out.println("Input must be a Binary value");
System.out.print("\nInput a binary number: ");
setCurrentValueInBinary(scanner.nextLong());
}
}
The "2 space after :" in print(String s) bug in Netbeans?
In the line:
System.out.print("Input a freaking binary number: ");
delete the 2nd trailing space.

Categories