Java scanner: line separator is not recognized as an input - java

I have a Test class that creates a Scanner and reads a user's input. I want to recognize when a user pressed Enter, so I check if the next symbol of the input equals to lineSeparator. However, even though I do press Enter it doesn't get recognized as such.
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
if (reader.next().equals(System.lineSeparator())) {
System.out.println("finished");
}
/but at the same time, this one works as expected:
String temp = "dog" + System.lineSeparator() + "cat";
System.out.println(temp);
}
}
At the same time when I construct a string using lineSeparator, it works fine, adding a new line as expected.
What is wrong here and how to recognize if a user pressed Enter?

change your code to use hasNextLine() to check if nextline exists and then nextLine() to read the nextLine. Something like this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
System.out.println("finished");
}

Related

How do I process different delimiters in a RegEx expression with Java?

I am working on creating a program for my course, in which I am required to divide the string: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;.
In the requirements, I need to read a single semicolon as a space, and a double semicolon as a new line. How do I create a regular expression in the useDelimiter() method that allows me to parse through and differentiate between both ; and ;;? Thank you!
Assignment Excerpt:
Instead of hard-coding the string, this time you will read it from the console. Study the useDelimiter() method and use it to set the delimiter for the scanner input. This time allow either colons or semicolons as the delimiters. One might prefer to use the String Tokenizer here, but don’t -- use the Scanner’s useDelimiter() method to set the delimiter in the Scanner and process each token as it comes.
import java.util.Scanner;
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in);
// Prompts user for input.
System.out.println("Enter the string you wish to filter & parse: ");
// Reads user input.
String filterString = input.nextLine();
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString);
a.useDelimiter(";|;;");
System.out.printf("\n");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next());
}
}
}
The Expected output is to be:
You may use this code:
public class Hw3p2 {
public static void main(String[] args) {
// Initializes scanner class.
Scanner input = new Scanner(System.in).useDelimiter(";;");
// Prompts user for input.
System.out.print("Enter the string you wish to filter & parse: ");
// Reads user input.
while(input.hasNext()) {
String filterString = input.next();
//System.err.println("filterString: " + filterString);
// Initiates new scanner reading the user inputted string.
Scanner a = new Scanner(filterString).useDelimiter(";");
// Loop that parses through string while there are more tokens.
while(a.hasNext()) {
System.out.print(a.next() + " ");
}
System.out.println();
a.close();
}
input.close();
}
}
Output:
Enter the string you wish to filter & parse: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;
This is the first line
This is the second line!
Done!
Note use of outer scanner with delimiter ;; and an inner one with ;.

Program that returns input \t as *

The code is supposed to read an unidentified number of inputs from the keyboard and return any tabs as *. My program seems to work when I run it in eclipse and get no errors. When I turn in the code on the submission website, this is the error I get.
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1589) at replaceHW.main(replaceHW.java:9)
import java.util.Scanner;
public class replaceHW {
public static void main(String[] args) {
//write a program that converts all TABS in your code
//with STARS i.e. *
Scanner in = new Scanner(System.in);
String ans;
while(!(ans = in.nextLine()).equals(""))
System.out.println(ans.replace("\t","*"));
}
}
Your problem is simple: nextLine() works in tandem with hasNextLine(): the correct code is:
try (Scanner in = new Scanner(System.in)) {
while (in.hasNextLine()) {
String line = in.nextLine();
if (!"".equals(line)) {
System.out.println(ans.replace("\t","*"));
}
}
The try-with-resources is best practice. But be wary than with System.in, it will close it when done.
hasNextLine() will try to read has much input is needed to find a line.

Exception when you are suppose to enter something in user input, but hit the enter/return key instead

I am writing a piece of code in JAVA that needs to handle every possible input. I am stuck on how to throw an exception or handle the case when user do not enter anything but just hit a enter/return key instead.
I guess you are using Scanner#next instead of Scanner#nextLine method. The following code prints 'empty' line for the first input, but for the next one it waits till a non-whitespace input is provided.
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("NextLine = " + s);
s = sc.next();
System.out.println("Next = " + s);
}
}

Can I input all the command at once?

I implemented a java program with some methods. Next I created a main class which will call the related method by entering a word.
for example:
Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
A<--this is the user input
Enter Number:<--the first Scanner input of method A
123<--Input 1
Enter words:<-- the second Scanner input of method A
ABC<--Input 2
123ABC<--The output method A
Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
B<--this is the user input
Enter Number 1:<--the first Scanner input of method B
100<--Input 1
Enter Number 2:<-- the second Scanner input of method B
50<--Input 2
150<--The output method B
Code of Method A {
String output;
private static Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Number:");
String no = keyboard.nextLine();
System.out.println("Enter Words:");
String words = keyboard.nextLine();
//do something...
System.out.println(output);
}
Code of Main class{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
Main main = new Main();
main.run();
}
public void run() {
boolean running = true;
while (running) {
displayMenu();
String command = keyboard.nextLine();
String[] parts = command.split("^");
if ("A".equalsIgnoreCase(command)) {
//call method A
} else if ("B".equalsIgnoreCase(command)) {
//call method B
} else if....etc
System.out.println();
}
what I want is input
A123 , ABCB100,50 at once
then the system will print the output of method A (123ABC) and B (150) for me.
What I want is input A into "keyboard", input 123 into "no" and input ABC into "words" at once
How can I do it?
As long as your don't close your Scanner (or its underlying input stream), the yet-to-read tokens will remain accessible for later use : read two lines (or 4 tokens - the comma is one) and "B\n100,50" will remain.
If you're asking how to provide this kind of input, it depends on your invokation method. If executed from bash, I'd use the following :
echo """A
123 , ABC
B
100,50""" | java ...
If you're asking how to dynamically invoke a method from its name, check the reflection API. Oracle's tutorial is a good resource in my opinion, here's a link to its section on retrieving and invoking methods.
There are 2 ways to do that.
First:
Instead of giving input directly in the console, first write all the data input somewhere and just copy it and paste it in the console.
Second:
You can use hasNexLine() and send EOF through keyboard by pressing ctrl+d.
Code:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while(s.hasNextLine())
{
sb.append(s.nextLine());
}
System.out.println(sb.toString());
}
Provide all your input and press ctrl+d to stop taking input.

Why won't Java print last word here?

Why does this print the entire string "1fish2fish"...
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String input = "1,fish,2,fish";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
But this only prints "1fish2" even though I enter "1,fish,2,fish"?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter your string: ");
Scanner sc = new Scanner(System.in);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
}
}
In the first case, the scanner doesn't need the last delimiter, as it knows that there are no more characters. So, it knows that the last token is 'fish' and there are no more characters to process.
In the case of a System.in scan, the fourth token is considered as completed only when the fourth ',' is entered in the system input.
Note that white spaces are considered as delimiters by default. But, once you specify an alternate delimiter using useDelimiter, then white space characters don't demarcate tokens any more.
In fact, your first trial can be modified to prove that white space characters are not delimiters any more...
public static void main(String[] args) {
String input = "1,fish,2,fish\n\n\n";
Scanner sc = new Scanner(input);
sc.useDelimiter(",");
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.print(sc.nextInt());
System.out.println(sc.next());
System.out.println("Done");
sc.close();
}
The new line characters will be treated as part of the fourth token.
I checked the first snippet; it is correctly printing -
1fish
2fish
Link - http://code.geeksforgeeks.org/jK1Mlu
Please let us know if your expectation is different.
Scanner waits for you to enter another ',' so when you will enter ',' then after that it will immediately prints fish after 1fish2.
so Pass 1,fish,2,fish, instead of 1,fish,2,fish

Categories

Resources