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.
Related
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.
EDIT: Sorry, I changed the code to reflect my problem. I have tried using scan.nextLine() and it is not working, which is strange to me.
I am trying to scan in the following String and save into a String variable called "tweet." :
"#typ offer; #det free essential supplies 4 evacs pets.; #loc
2323 55th st, boulder; #lat 40.022; #lng -105.226;"
However when I print the final tweet string, it only saves the first line, all the way to #loc. It doesn't include the 2323 55th st, boulder; #lat 40.022; #lng -105.226;" part of the string. Is there something besides nextLine() I should be using?? Here is my code and output.
Scanner scan = new Scanner(System.in);
String tweet = null;
String type, detail, location, latitude, longitude = null;
int start, finish = 0;
tweet = scan.nextLine();
System.out.println(tweet);
The output that I get is: "#typ offer; #det free essential supplies 4 evacs pets.; #loc
However it is missing the second part of the string. Probably a super easy fix, but thanks for the help in advanced.
You seem to be using scan.next();, not scan.nextLine(). Maybe that's a typo, but if that's the code, try changing it.
Use
tweet = scan.nextLine();
It'll work.
You are using next() that will give you the next token. What you should use is nextLine() that will give you all the line.
EDIT:
You said that using nextLine() is not working, that's weird because it works. Are you sure you are not copying and pasting the sentence? Maybe it has a CRLF. Try writing the sentence.
scan.next(); method finds and returns the next complete token from this scanner(until it hit the first space it will end).
Output will be:
"#typ
you need to use scan.nextLine();,
If you use nwxtLine() output will be:
"#typ offer; #det free essential supplies 4 evacs pets.; #loc 2323 55th st, boulder; #lat 40.022; #lng -105.226;"
read doc.
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);
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).
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.