Search code examples
javaindexof

I am trying to find a space in the string entered by the user but when I use indexof(" ") it returns -1 for the value, how do I fix this?


System.out.println("Please enter your first and last names separated by a space: "); try (Scanner scan = new Scanner(System.in)) { String s1 = scan.next();

            int space = s1.indexOf(" ");
        
                String First_Name = s1.substring(0,space);
                String init1 = First_Name.substring(0,1);
                String Last_Name = s1.substring(space+1,s1.length());
                String init2 = Last_Name.substring(0,1);
        
        
                    int First_N = First_Name.length();
                    int Last_N = Last_Name.length();
        
                        System.out.println("You entered the name "+s1+".");
                        System.out.println("Your first name "+First_Name+": has "+First_N+" characters.");
                        System.out.println("Your last name "+Last_Name+": has "+Last_N+" characters.");
                        System.out.println("Your initials are "+init1+init2+".");

Solution

  • You should use

    String s1 = scan.nextLine();
    

    instead of

    String s1 = scan.next();