Search code examples
javastringsubstringindexofsentence

Java sentence shortening program doesn't work right


import java.util.Scanner;
public class SentenceShortener {

    public static void main(String[] args) {
        
        Scanner kbd = new Scanner(System.in);
        String sentence = "";
        String sentence2 = "";
        String sentence3 = "";
        String finalcount = "";
        
        System.out.println("Input sentence ");
        
        sentence = kbd.nextLine();
        int space = sentence.indexOf(" ");
        System.out.println(sentence.substring(space+1));
        
        sentence2 = sentence.substring(space+1);
        int space2 = sentence.indexOf(" ");
        System.out.println(sentence2.substring(space2+1));
        
        sentence3 = sentence2.substring(space2+1);
        int space3 = sentence2.indexOf(" ");
        System.out.println(sentence3.substring(space3+1));
        
        finalcount = sentence3.substring(space3+1);
        
        System.out.println("Your " + sentence.length() + " character long sentence was shortened to " + finalcount.length() + " characters.");
    }

}

I created a program that should shorten four word sentences and longer down to decreasingly shorter "sentences" and counts how many characters you shortened the sentence to.

Here is how it should work:

Input sentence
The car runs good.
car runs good.
runs good.
good.
Your 18 character long sentence was shortened to 6 characters.

How it actually runs:

Input sentence 
The car runs good.
car runs good.
runs good.
 good.
Your 18 character long sentence was shortened to 6 characters.

Another run:

Input sentence 
Why is it raining?
is it raining?
t raining?
aining?
Your 18 character long sentence was shortened to 7 characters.

I'm a beginner with Java.


Solution

  • Logic to determine index of space is incorrect. Try modifying your code to have

    int space2 = sentence2.indexOf(" ");
    int space3 = sentence3.indexOf(" ");