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.
Related
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.
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.
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.
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.
Having trouble using StdIn.readString() from algs4 Princeton Algorithm Course in Eclipse.
String item2 = "test1";
item2 = StdIn.readString();
System.out.println("test2");
The program would not execute any codes after StdIn.readString();
How would the method StdIn.readString() take the string input?
Stack overflow says "Run Configuration" -> "Arguments". But it doesn't seem to work for me.
Resolved: As cricket_007 says, it was waiting for my input in the Eclipse console.
Answering this in 2020 just in case anybody is still wondering. As cricket_007 said, StdIn.readString() waits for console input. To add to his answer, StdIn.readString() will only read the first token. In order for all tokens to be read, StdIn.readString() should be ran in a loop.
while (!StdIn.isEmpty()) {
string value = StdIn.readString();
StdOut.println(value);
}
The above is referenced here https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html
The program would not execute any codes after StdIn.readString();
It is waiting for user input. You have to actually type something and press Enter in the Eclipse console.
Try running this, for example
System.out.print("Type Here >>> ");
item2 = StdIn.readString();
System.out.println("You entered: " + item2);