0

I am a trying to create a program that takes input from the user (assuming 3 words) and outputs the first word capitalised, the second in lower case and the third word only the first two characters. I don't understand why the third one is printed whole plus the first two characters and not just the first 2 characters. Thanks so much! So far I have this:

import java.util.Scanner;

public class Words {

    public static void main (String[] args){

        Scanner keyboard = new Scanner(System.in);

        String line = keyboard.nextLine();

        String word1 = line.substring(0, line.indexOf(" ")).toUpperCase();
        String word2 = line.substring(line.indexOf(" ") +1).toLowerCase();
        String word3 = line.substring(line.lastIndexOf(" ")+1).substring(0, 
        ,2);

        System.out.println(word1 + " " + word2 + " " + word3);
    }

}

Output:

JAVA is fun fu

Parijat Purohit
  • 921
  • 6
  • 16
  • This is not a duplicate. I'm trying to find out how to split a string into words with the means of method indexOf not accessing characters with this method. Thanks – Diana Constantina Nov 04 '17 at 20:24

1 Answers1

2

You say

String word2 = line.substring(line.indexOf(" ") +1).toLowerCase();

which makes word2 assume the value of is fun. Also, for word 3, you say .substring(0,2) (as substring's 2nd number is non-inclusive) which brings in the fu, creating the output JAVA is fun fu.

An alternative implementation could be to just Split the string by space and assign it to the three variables easily.

Parijat Purohit
  • 921
  • 6
  • 16
  • Like so: String s[] = line.split(" "); String word1 = s[0].toUpperCase; String word2 = s[1].toLowerCase; String word3 = s[2]; // Check if word3 contains at least 2 characters: word3 = word3.substring(0, Math.min(2, word3.length())); System.out.println(word1 + " " + word2 + " " + word3); – Heiko Jakubzik Nov 04 '17 at 20:25
  • @HeikoJakubzik You should not feed code: at least that is what I feel. You should give enough subtle hints to the questioner so that he can think through his code, realize his mistakes, correct them and learn :) – Parijat Purohit Nov 04 '17 at 20:29
  • I don't want to resort to a solution where I use an array but I am trying to use of indexOf method to set the boundaries for each token. – Diana Constantina Nov 04 '17 at 20:29
  • @DianaConstantina yes, and parts of your code can be improved to make it happen (Based upon my answer). You need to define the ending index of the second word. Substring without the ending index assumes the entire string that follows. Something like `line.substring(line.indexOf(" ") +1, line.lastIndexOf(" ")).toLowerCase();` should work. – Parijat Purohit Nov 04 '17 at 20:34
  • 1
    Thanks so much Parijat Purohit! It does work indeed! – Diana Constantina Nov 04 '17 at 20:48
  • @DianaConstantina glad I could help. :) – Parijat Purohit Nov 04 '17 at 20:52