Convert a sentence to an array in Java - java

How can I convert a sentence to an array?
I have this code:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your sentence: ");
String sentence = scanner.next();
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
But... all this does is just print out the first word of the array and thats it.

Scanner.next()
reads only the next token - not the next line. You want: Scanner.nextLine()

I've added a debugging statement that should make clear a pretty big problem:
import java.util.Scanner;
public class SentenceToWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your sentence: ");
String sentence = scanner.next();
//USEFUL INFORMATION!!!
System.out.println("sentence=\"" + sentence + "\"");
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
}
}
Output:
[C:\java_code\]java SentenceToWords
Enter your sentence: setao uhesno uhoesuthesao uh
sentence="setao"
setao
As stated by #Makoto: You're only reading in a word, when you want to read in a line.

next is only literally consuming the next String. Use nextLine instead.
String sentence = scanner.nextLine();
The reason: nextLine() advances the scanner past the newline, which means that it captures the entire line.

It is happening because you are using Scanner, which ignores a string after a space, if you use next(). Use nextLine() instead.

Related

Terminating Java User Input While Loop

I am learning Java day 1 and I have a very simple code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String word = input.next();
System.out.println(word);
}
}
After I input any sentence, the while loop seems to not terminate.
How would I need to change this so that the I could break out of the loop when the sentence is all read?
The hasNext() method always checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern that matches whitespace by default.
Whitespace includes not only the space character, but also tab space (\t), line feed (\n), and more other characters
hasNext() checks the input and returns true if it has another non-whitespace character.
Your approach is correct if you want to take input from the console continuously. However, if you just want to have single user input(i.e a sentence or list of words) it is better to read the whole input and then split it accordingly.
eg:-
String str = input.nextLine();
for(String s : str.split(" ")){
System.out.println(s);
}
Well, a simple workaround for this would be to stop whenever you find a stop or any set of strings you would like!
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String word = input.next();
if (word.equals("stop")) {
break;
}
System.out.println(word);
}
input.close();
System.out.println("THE END!");

String Manipulation - Removing the charachters of the second word to the first word

Enter two words: computer program
result: cute
the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute"
thought of using replaceAll but could not make it work.
String sentence;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 words: ");
sentence = input.nextLine();
String[] arrWrd = sentence.split(" ");
String scdWrd = arrWrd[1];
String fnl = arrWrd[0].replaceAll(scdWrd, "");
System.out.println(fnl);
.replaceAll takes a regex, so basically what you are doing here is you're searching for the whole "program" word and replacing it and not its characters, so you just need to add brackets to your scdWrd to let it know that you want to replace the chars:
String scdWrd = "[" + arrWrd[1] + "]";
Just to add to the elegant solution by #B.Mik, you should also check for things like
If multiple spaces are entered between the words.
If the user enters a blank line or just one word e.g. execute your program and enter a blank line or just one word e.g. computer and you will be welcomed with java.lang.ArrayIndexOutOfBoundsException.
The program given below addresses these points:
import java.util.Scanner;
public class LettersFromSecondReplacement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid;
String input;
String words[];
do {
valid = true;
System.out.print("Enter two words separated with space: ");
input = in.nextLine();
words = input.split("\\s+"); //Split on one or more spaces
if (words.length != 2) {
System.out.println("Error: wrong input. Try again");
valid = false;
}
} while (!valid);
for (String s : words[1].split("")) { //Split the 2nd word into strings of one character
words[0] = words[0].replaceAll(s, "");
}
System.out.println(words[0]);
}
}
A sample run:
Enter two words separated with space:
Error: wrong input. Try again
Enter two words separated with space: computer
Error: wrong input. Try again
Enter two words separated with space: computer program
cute
Note that I have used a different algorithm (which you can replace with the one provided by #B.Mik) for replacement. Feel free to comment in case of any doubt/issue
replace line with replaceAll by
String fnl = arrWrd[0];
for (byte c : scdWrd.getBytes()) {
fnl = fnl.replace("" + (char)c, "");
}

Getting a name as an input using regex in java

I am a beginner in both, Java and regular expressions. I want to get a name as an input, by which I mean that only names that have English alphabets A-Z, case insensitive and spaces.
I am using a Scanner class to get my input but my code doesn't work. It looks like:
Scanner sc= new Scanner(System.in);
String n;
while(!sc.hasNext("^[a-zA-Z ]*$"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
I checked my regular expression on the website regex101.com and found out that it works fine.
For example, If I input it my name, Akshay Arora , the regex site says it is okay but my program prints
That's not a name
That's not a name
Same line is printed twice and it again asks me for input. Where am I going wrong?
Two parts are wrong:
$ and ^ anchors are considered in the context of entire input, not in the context of the next token. It will never match, unless the input has a single line that matches the pattern in its entirety.
You use default delimiters, which include spaces; therefore, Scanner will never return a token with a space in it.
Here is how you can fix this:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;
while(!sc.hasNext("[a-zA-Z ]+"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
Demo.
Here its sample program related to regex.
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String regex = "^[a-zA-Z ]*$";
// Compile this pattern.
Pattern pattern = Pattern.compile(regex);
// See if this String matches.
Matcher m = pattern.matcher(inputName);
if (m.matches()) {
System.out.println("Valid Name");
} else
System.out.println("Invalid Name");
}
}
Hope this will help you

Java: taking only the first word of a user input string

Homework question that I've been having a little trouble with...
I need to have a user input string as a product category. If the user inputs more than one word, I need to take only the first word typed.
Stipulation: I cannot use 'if' statements.
Here's what I have so far, but it fails if only one word is typed.
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a noun that classifies the"
+ " type of your product:");
String noun = scan.nextLine();
int n = noun.indexOf(" ");
String inputnoun = noun.substring(0,n);
Use string.split()
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a noun that classifies the"
+ " type of your product:");
String noun = scan.nextLine();
String inputnoun = noun.split(" ")[0];
You can use scan.next() to get only the first word.
The method split(String regex) in the string class will return an array of strings split on the regex string.
String test = "Foo Bar Foo Bar"
String[] array = test.split(" ");
//array is now {Foo, Bar, Foo, Bar}
From there you can figure out how to get the first word.
Next time you are stuck, the Java API pages are very helpful for finding new methods.
You can use String[] array = noun.split("\\s+"), to split between the spaces, and then use array[0] to return the first word.
Instead of manipulating the entire input String, another way is to use the delimiter of the Scanner class:
Scanner scan = new Scanner(System.in);
// Following line is not mandatory as the default matches whitespace
scan.useDelimiter(" ");
System.out.println("Enter a noun that classifies the"
+ " type of your product:");
String noun = scan.next();
System.out.println(noun);
Note that we are using next() instead of nextLine() of the Scanner class.

Only one word in println is shown and the rest do not

When I type a phrase into the console, only one word appears below the green text while the other words do not appear. Not sure what I am doing wrong here. Any help would be appreciated.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence or phrase. It can be anything you want it to be: ");
//ask user for sentence or phrase
String p1 = keyboard.next();
System.out.println(c1); //display user sentence or phrase
next() reads a single word1, use nextLine() to read the entire line.
1 Specifically, 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". The default delimiter is \s+, a continuous string of whitespace characters. You can change this delimiter via useDelimiter.
Change your code to this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence or phrase. It can be anything you want it to be: ");
//ask user for sentence or phrase
String p1 = keyboard.nextLine();
System.out.println(c1); //display user sentence or phrase
The problem is
keyboard.next();
only gets a single word. You need to use:
keyboard.nextLine();

Categories