0

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

4 Answers 4

4

Problem is not with the split method, rather you should use nextLine instead of next:

String sentence = sc.nextLine();
Sign up to request clarification or add additional context in comments.

1 Comment

But the problem with nextLine is If we want to take two inputs its skips the first input and takes the second input. That's what I am facing now if I am using next so split not working and if I use nextLine so it's not taking first input
0

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.

Comments

0

You can use the whitespace regex

str = "Hello spilt me";
String[] splited = str.split("\\s+");

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.