How do I check for \n when using java scanner? - java

I'm trying to write a scanner so that every time \n is detected, it will scan the line after that until a new \n shows up. I first tried something like this.
import java.util.Scanner;
public class test{
public static void main(String[] args) {
String input = "first line \nsecond line \nthird line";
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
sc.close();
}
}
Which works, and the output is
first line
second line
third line
However, when I try doing the same thing with Scanner(System.in) it doesn't work the same way even with same input
import java.util.Scanner;
public class test{
public static void main(String[] args) {
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
String input = cmd.nextLine();
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
cmd.close();
sc.close();
}
}
Output:
first \n second \n third
What should I change, so that every \n will print a new line?
EDIT:
If the input was
first
second
third
and entered into the prompt at once, would scanner.nextLine() be enough to suffice?

System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
while(cmd.hasNext()) {
String word = cmd.next();
if(word.equals("\\n")) {
System.out.println();
}else {
System.out.print(word);
}
}

In all honesty, you will need to utilize these sub-strings at some point outside of your while loop so it would actually be better to split the line based on the same delimiter and have each substring as a element within a String Array This way you don't need to utilize Scanner and a while loop for this at all, for example:
String input = "first line \n second line \n third line"; // Read in data file line...
String[] stuffArray = input.split("\\s+?\n\\s+?");
System.out.println(Arrays.toString(stuffArray));
System.out.println();
System.out.println(" OR in other words");
System.out.println();
for(String str : stuffArray) {
System.out.println(str);
}
If you want to do this using System.in:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text:");
String stuff = sc.nextLine();
String[] subArray = stuff.trim().split("(\\s+)?(\\\\n)(\\s+)?");
System.out.println();
// Display substrings...
for (String strg : subArray) {
System.out.println(strg);
}

Related

Java program takes input twice

So below is my code. I'm trying to use the Scanner class to read an input from the console, and then print out each token on a separate line. But there's a small problem where the user has to input twice. An example of what happens is given below the code
import java.util.Scanner;
public class StringSort {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
int i = 0;
while (i< str.length()) {
i++;
System.out.println("" + scanner.next());
}
scanner.close();
}
}
Example:
Enter a string:
what is love
what is love
what
is
love
To do what you want use the Scanner class to read an input from the console, and then print out each token on a separate line you can use the String::split method
String str = scanner.nextLine();
String [] arr = str.split (" ");
for (String x : arr) {
System.out.println (x);
}
A more efficient implementation of the above code would be as follows:
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
System.out.println(sc.next());
}
This would avoid use of extra space as done by #ScaryWombat
Scanner should be propertly closed:
try (Scanner sc = new Scanner(System.in)) {
while (sc.hasNext()) {
System.out.println(sc.next());
}
}

scanner does not read after space character

I have 2 inputs from user. One is say greetings and the other one is tell me your name
But when I write after something hello, ex: Hello mate!! Scanner does not read the second input which is mate and takes hello from first string second one is also same
any advice
Thanks
public static void main(String[] args) {
System.out.println("Choose what would you like to say ?");
String str1 = "";
String str2 = "";
System.out.println("Say any greetings word");
str1 = input();
System.out.println("Tell me your name");
str2 = input();
if (str2.equalsIgnoreCase("zia")) {
System.out.println("Hello Mr Zia, What a nice suprise");
}
else {
System.out.println(str1 + " " + str2);
}
}
public static String input() {
Scanner sc = new Scanner(System.in);
return sc.next();
}
First of all, you need sc.nextLine() to read the whole input.
Second, you shouldn't create a new scanner every time. Just re-use the scanner like this:
Scanner sc = new Scanner(System.in);
System.out.println("Say any greetings word");
str1 = sc.nextLine();
System.out.println("Tell me your name");
str2 = sc.nextLine();
And close the scanner if you don't need it any more:
sc.close();
That way you don't even need the input()-method any more.
You cannot build more than one Scanner on the same input stream. They will conflict with each other, leading to the inconsistencies you're observing.
With your program as shown every call to the method input() will build a new Scanner on the one unique System.in. That's more than one Scanner on the same input stream. Won't work.
Instead, build one Scanner once and for all, at the very beginning of your program, and use that one unique Scanner every time you need to read input.
Like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose what would you like to say ?");
System.out.println("Say any greetings word");
String greeting = scanner.next();
System.out.println("Tell me your name");
String name = scanner.next();
if (name.equalsIgnoreCase("zia")) {
System.out.println("Hello Mr Zia, What a nice suprise");
} else {
System.out.println(greeting + " " + name);
}
}

parsing Strings in java

The same question was asked before but I the help wasn't sufficient enough for me to get it solved. When I run the program many times, it goes well for a string with comma in between(e.g. Washington,DC ). For a string without comma(e.g. Washington DC) the program is expected to print an error message to the screen and prompt the user to enter the correct input again. Yes, it does for the first run. However, on the second and so run, it fails and my suspect is on the while loop.
Console snapshot:
Enter input string:
Washington DC =>first time entered & printed the following two lines
Error: No comma in string.
Enter input string:
Washington DC => second time, no printouts following i.e failed
Here's my attempt seeking your help.
public class practice {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput = "";
String delimit =",";
boolean inputString = false;
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while (!inputString) {
if (userInput.contains(delimit)){
String[] userArray = userInput.split(delimit);
// for(int i=0; i<userArray.length-1; i++){
System.out.println("First word: " + userArray[0]); //space
System.out.println("Second word:" + userArray[1]);
System.out.println();
//}
}
else if (!userInput.contains(delimit)){
System.out.println("Error: No comma in string.");
inputString= true;
}
System.out.println("Enter input string:");
userInput = scnr.nextLine();
while(inputString);
}
}
}
You can easily solve this problem using a simple regex ^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$
So you can check the input using :
boolean check = str.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$");
Then you can use do{}while() loop instead, so your code should look like this :
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userInput;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
} while (!userInput.matches("^[A-Z][A-Za-z]+, [A-Z][A-Za-z]+$"));
}
regex demo
Solution 2
...But I can't apply regex at this time and I wish others help me to
finish up the work the way I set it up
In this case you can use do{}while(); like this :
Scanner scnr = new Scanner(System.in);
String userInput;
String delimit = ",";
boolean inputString = false;
do {
System.out.println("Enter input string:");
userInput = scnr.nextLine();
if (userInput.contains(delimit)) {
String[] userArray = userInput.split(delimit);
System.out.println("First word: " + userArray[0]);
System.out.println("Second word:" + userArray[1]);
System.out.println();
} else if (!userInput.contains(delimit)) {
System.out.println("Error: No comma in string.");
inputString = true;
}
} while (inputString);

Why using sc.nextLine() isn't the correct way to transfer control to next line of input ?

I was solving HackerRank "30 Days Of Code" problem 8.
This is the code I wrote:
import java.util.*;
import java.io.*;
public class Directory
{
public static void main(String args[])throws NoSuchElementException
{
Scanner sc=new Scanner(System.in);
//System.out.println("Enter number");
int n=sc.nextInt();
sc.nextLine();
Map<String,String> Directory= new HashMap<String,String>();
for (int i=0;i<n;i++)
{
//System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
Directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = Directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}
}
When I run this code with the custom input I get an error as follows:
Exception in thread "main" java.util.NoSuchElementException: No line
found at java.util.Scanner.nextLine(Scanner.java:1585) at
Directory.main(Directory.java:23)
I think this is occurring due to the "sc.nextLine()" in the while loop. But I'm not able to figure out why. I had learnt from here that I should use sc.nextLine() after using sc.next() so that the control is transferred to the next line of input. Any ideas where I am going wrong?
From Documentation:
public String next() Finds and returns the next complete token from
this scanner. A complete token is preceded and followed by input that
matches the delimiter pattern
And also from the Documentation of Scanner:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace
And whitespace includes \n and \r.
So as a conclusion, using nextLine() to workaround the newline problem is valid in case of nextInt() but it is not in case of using next().
I think this will work for you. Try it :)
You do not need this line sc.nextLine();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter number");
int n=sc.nextInt();
Map<String,String> directory= new HashMap<>();
for (int i=0;i<n;i++)
{
System.out.println("Enter name and phone number");
String name=sc.next();
String ph=sc.next();
sc.nextLine();
directory.put(name,ph);
}
while(sc.hasNext())
{
String s = sc.next();
sc.nextLine();
String phoneNumber = directory.get(s);
System.out.println((phoneNumber != null) ? s + "=" + phoneNumber : "Not found");
}
}

How to get the second word from Java Scanner input?

Maybe it just requires a method of String but I really need to get the value of the second word from Scanner input received like this:
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
Assuming you're defining "word" as the part split off by a space, and there are exactly two words entered:
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
String secondWord = a.substring(a.indexOf(" "));
If there may be more, use split:
Scanner in = new Scanner(System.in);
String a;
a = in.nextLine();
String secondWord = a.split("\\s+")[1];
Use http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-
like this a.split(" ") the result will be array of size 2, where second element will be results.txt
You can use scanner.next(). A unit test case to demonstrate:
#Test
public void testSecondWordSingleLine() {
Scanner scanner = new Scanner("hello hi there");
scanner.next();
assertEquals("hi", scanner.next());
}
It works also if the second word is on a new line, for example:
#Test
public void testSecondWordMultiLine() {
Scanner scanner = new Scanner("hello\nhi there");
scanner.next();
assertEquals("hi", scanner.next());
}
#Test
public void testSecondWordMultiLineWithNextLineFirst() {
Scanner scanner = new Scanner("hello\nhi there");
scanner.nextLine();
assertEquals("hi", scanner.next());
}

Categories