Question

For this program it asks for the user to input their full name. It then sorts out the first name and last name by separating them at the space the put between the first and last name. However, indexOf() is not recognizing the space and only returns -1. Why is that? Thanks.

Here is the prompt off of PracticeIt:

Write a method called processName that accepts a Scanner for the console as a parameter and that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:

Please enter your full name: Sammy Jankis

Your name in reverse order is Jankis, Sammy

import java.util.*;

public class Exercise15 {

public static void main(String[] args) {
    Scanner inputScanner = new Scanner(System.in);
    processName(inputScanner);

}

public static void processName(Scanner inputScanner) {
    System.out.print("Please enter your full name: ");
    String fullName = inputScanner.next();

    int space = fullName.indexOf(" "); // always return -1 for spaces
    int length = fullName.length();

    String lastName = fullName.substring(space+1,length+1);
    String firstname = fullName.substring(0, space);

    System.out.print("Your name in reverse order is " + lastName + ", " + firstname);
}
}
Was it helpful?

Solution 2

When you do String fullName = inputScanner.next() you only read till the next whitespace so obviously there is no whitespace in fullName since it is only the first name.

If you want to read the whole line use String fullName = inputScanner.nextLine();

OTHER TIPS

As next will return the next token use nextLine not next to get the whole line

see http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top