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.
Related
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!");
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, "");
}
String getname(){
Scanner input = new Scanner(System.in);
String name;
System.out.println("Enter your name:");
name= input.next();
String name_pattern = "^[A-Za-z]+(\\s[A-Za-z]+)$";//this regex isnt validating Ben Smith
Pattern pattern = Pattern.compile(name_pattern);
Matcher regexmatcher = pattern.matcher(name);
if(!regexmatcher.matches()){
System.out.println("Name format not correct");
}
return name;
}
I also need to take the input again and again until the correct format is entered. How do i do that? My current regex prints "Name format not correct" when I input "Ben Smith" though it should not print that because Ben Smith is a valid input!
input.next returns the next token from the input rather than the next line. You may set another delimiter in Scanner to return lines but the most custom way is to use
name= input.nextLine();
The Scanner's next() method returns only the next word, in your case "Ben". Replace that with nextLine() to get the whole name.
Scanner input = new Scanner(System.in);
String name;
System.out.println("Enter your name:");
name = input.nextLine();
With that your regular expression matches "Ben Smith".
^[A-Za-z ]+$ is enough.
private final static Pattern NAME_VALIDATOR = Pattern.compile("^[A-Za-z ]+$");
[...]
System.out.println(NAME_VALIDATOR.matcher("Ben Smith").matches());
Note that the Pattern is always the same, so you can just create it once instead of creating it every time you enter the method.
Also note that this will not validate names with ', e.g. O'Brian, neither foreign names, e.g. Mätthaus. Consider using \p{L} instead.
As a comment points out:
"As far as I understand they want only two words with a space
inbetween to be valid"
Then the regex would be "^[A-Za-z]+ [A-Za-z]+$" instead.
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.
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();