How to get the second word from Java Scanner input? - java

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());
}

Related

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

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);
}

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 can't I enter a string in Scanner(System.in), when calling nextLine()-method?

How does this program actually work...?
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is ="+a);
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is="+s);
}
}
The output is:
enter the no
1234
no is 1234
enter a string
string is= //why is it not allowing me to enter a string here?
.nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.
You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int.
This is a common misunderstanding which leads to confusion if you use the same Scanner for nextLine() right after you used nextInt().
You can either fix the cursor jumping to the next Line by yourself or just use a different scanner for your Integers.
OPTION A: use 2 different scanners
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner intscan =new Scanner(System.in);
System.out.println("enter a no");
a=intscan.nextInt();
System.out.println("no is ="+a);
Scanner textscan=new Scanner(System.in);
System.out.println("enter a string");
s=textscan.nextLine();
System.out.println("string is="+s);
}
}
OPTION B: just jump to the next Line
class string
{
public static void main(String a[]){
int a;
String s;
Scanner scan =new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is ="+a);
scan.nextLine();
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is="+s);
}
}
You only need to use scan.next() to read a String.
This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:
You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
You can use the next method on the scanner object as
scan.next();
Scanner's buffer full when we take a input string through scan.nextLine();
so it skips the input next time .
So solution is that we can create a new object of Scanner , the name of the object can be same
as previous object......
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
use a temporary scan.nextLine(); this will consume the \n character
if you don't want to use parser :
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
scan.nextLine(); // This line you have to add (It consumes the \n character)
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is=" + s);
Incase you don't want to use nextint, you can also use buffered reader, where using inputstream and readline function read the string.
Simple solution to consume the \n character:
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is ="+a);
scan.nextLine();
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is="+s);
}
}
import java.util.*;
public class ScannerExample {
public static void main(String args[]) {
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
System.out.println("enter a string");
s = scan.next();
System.out.println("string is=" + s);
}
}
.nextInt() will not read the 'nextline' till the end if you declare .nextLine() after it.
I would recommend try to scan 'String' before 'int'
s = scan.nextLine();
a = scan.nextInt();
In that order.
s=scan.nextLine();
It returns input was skipped.
so you might use
s=scan.next();

Categories