Trying to split out a string and output the penultimate word inputted by the user, but the .split() only seems to be outputting a single string into the array so its not working?
import java.util.*;
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}
Problem is not with the split method, rather you should use nextLine instead of next:
String sentence = sc.nextLine();
The answer by #Aomine should resolve your problem. If you really wanted to use Scanner#next() directly, then you could also try setting the scanner's delimiter to be newline:
Scanner sc = new Scanner (System.in);
sc.useDelimiter(Pattern.compile("\\r?\\n"));
Then, calling Scanner#next() should default to returning the next full line.
You can use the whitespace regex
str = "Hello spilt me";
String[] splited = str.split("\\s+");
The split is working correctly. Reading of information from console is correct. Below changes should work.
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
for (String currentWord : words ) {
System.out.println("The current word is" + currentWord);
}
}}
Related
I wan't to use the scanner to ask for input a few words and am expecting a delimiter ", " to separate each word.
I then want to split each word and store it in an array so I could use it for other purposes i.e, instantiate an object with an array argument for my constructor.
Could someone help me please
Update: I have resolved the problem! Thanks everyone for the suggestions.
If I understand your question correctly, this is that I would do
Scanner keyb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = keyb.nextLine();
String[] stringArray = input.split(",");
To see the results:
for(int i=0; i < stringArray.length; i++){
System.out.println(i + ": " + stringArray[i]);
}
This will work for any size sentence as long as each word is separated by a ,.
import java.util.*;
public class testing {
public static void main (String[] args) {
String splitter = ",";
Scanner scanner = new Scanner(System.in);
System.out.println("user input:");
String[] fewwords = scanner.nextLine().split(splitter);
System.out.println(fewwords[0] + fewwords[1] + fewwords[2]);
}
}
You can do this using a loop and checking with Scanner.hasNext(). Like so:
Scanner k = new Scanner(new File("input.txt"));
k.useDelimiter(",");
LinkedList<String> words = new LinkedList<String>();
while(k.hasNext()){
words.add(k.next());
}
System.out.println(words);
Notice how I set the delimiter to be a comma, so that each next read word is distinguished as being separated by commas.
So basically what I need help I need help doing is removing a word from a sting. I dont know how to use array, char and such just for those who refer me to that.
Output Ex:
Enter a sentence: I really like Jolly Ranchers.
Enter a string: really
I like Jolly Ranchers.
I just need to remove every occurrence of the string from the sentence essentially. Thanks for help in advance!
(Not looking for a handout, perhaps pseudocode or another example.)
Use replaceAll function,
this function gets two params
regex - the string you want to replace
substr- the string to replace it with
example:
newString = str1.replaceAll(regex, substr);
newString is the edited string
str1 is the string you wish to edit
String.replaceAll works for that
package se.samples;
import java.util.Scanner;
public class WordRemover {
static final String welcomeMessage = "Enter a sentence: ",
secondMessage = "Enter a string: ",
resultMessage = "";
static String replace(String source, String that){
return source.replaceAll(that, "");
}
public static void main(String[] args) throws Exception {
System.out.print(welcomeMessage);
try(Scanner s = new Scanner(System.in)){
String input = s.nextLine();
System.out.print(secondMessage);
System.out.println(resultMessage + replace(input, s.nextLine()));
}
}
}
You can go this way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
String res ="";
for(String words : sentence.split(" ")){
if(!words.equalsIgnoreCase(word)){ //or words!=word if you want to NOT ignore the case
res+=words+" ";
}
}
return res;
}
public static void main(String[] args) {
System.out.println(remove());
}
It looks every word, and keep only the ones who are not equals to the word you enter
Or a more with a more shorter way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
return sentence.replaceAll(word,"");
}
Please try this
String[] s = originalString.split(" ");
String wordToRemove = StandardInput;
String finalString ="";
for(String word : s){
if(!word.equals(wordToRemove )){
System.out.Print(word);
finalString += word+" ";
}
}
I believe strings have a replace method so try something like str.replace("really", "") or replaceEach if there will be more than one. I suggest looking at the Java API for more functions.
I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little
I want to be able to output the letter size of each word. So far my code only outputs the letter size of the first word. How do I get it to output the rest of the words?
import java.util.*;
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String words = sc.next();
String[] letters = words.split(" ");
for (String str1 : letters) {
System.out.println(str1.length() );
}
}
}
It's just because next returns only the first word (or also called the first 'token'):
String words = sc.next();
To read the entire line, use nextLine:
String words = sc.nextLine();
What you are doing should work then.
The other thing you can do is go ahead and use next all the way (instead of a split) because Scanner already searches for tokens using whitespace by default:
while(sc.hasNext()) {
System.out.println(sc.next().length());
}
Using sc.next() will only let the scanner take in the first word.
String words = sc.nextLine();
Iterate over all of the scanner values:
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String word = sc.next();
System.out.println(word.length() );
}
}
}
I'm trying to find the smallest word in a user entered string. This is what I have so far:
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;
shortestLength=(myWords[0]).length();
shortestLocation=0;
for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
If I entered "SMALLEST WORD SHOULD BE A", the output should be A but it just gives me the first word of the string. Any ideas?
Your algorithm is fine, but instead of using next():
String myText = sc.next();
Which will only read a single token, i.e., the first word, use nextLine(), which will read the entire line:
String myText = sc.nextLine();
To take the full string you have to use the method
sc.nextLine();
thus it will take the complete string.