Java program takes input twice - java

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

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

problem is while loop is not ending in taking input paragraph using system.in in Java

I am having problem in taking a hole paragraph as input in java using System.in and storing it in an array. but problem is with while loop is not ending and program stuck in the loop. i have tried many methods but loop is not ending.
Scanner sc = new Scanner(System.in);
ArrayList < String > al = new ArrayList<>();
System.out.print("Please Enter Paragraph + \n");
while (!(sc.equals(null))) {
al.add(sc.next());
}
Scanner sc = new Scanner(System.in);
String para = sc.nextLine();
int x = 0;
while (para != null) {
if (sc.hasNextLine()) {
ParaArray[x] = para;
para = sc.nextLine();
x++;
} else {
para = null;
}
}
sc is a Scanner object. When you compare sc with null, you will never get true because sc could never be null. Also, your code seems to have a lot of errors. Your question is also unclear. Please provide a proper question...
-Thanks
Tejan Gandhi
Dt: 29th July (After reading your comment):
There are 2 parts of code, one which scans characters and another scans lines.. Because the first "while" loop compares sc (which is a Scanner object) it can never be null and loop can never end.. So instead of doing
sc.equals(null)
sc.hasNext()
Tell me if that works for you.
when you use "sc.hasNextline",you should put"Scanner sc= new Scanner(System.in); " before your judgment statement,just like this:
int num = 0;
while (true) {
System.out.println("Please input a number");
Scanner sc = new Scanner(System.in);
if (sc.hasNextDouble()) {
num = sc.nextDouble();
} else {
System.out.println("It is not a number,please try again!");
System.out.println("============================");
}
}
After your first loop you have already an array of paragraphs so why it is not clear why you need a second loop.
I've also put the scanner in a try () because Scanner is Closeable so it is closed at the end.
import java.util.ArrayList;
import java.util.Scanner;
public class ScanTest {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
ArrayList<String> al = new ArrayList<>();
while (true) {
System.out.println("Please Enter Paragraph + \n");
String readLine = sc.nextLine();
if (readLine.length() == 0) {
break;
}
al.add(readLine);
}
System.out.println("result:"+al);
}
}
}

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

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