0

ORIGINAL QUESTION IS----Write a program in java to input a sentence which ends only with ! or ? .each word in the sentence is separated by single blank space. convert the sentence into upper case and remove extra blank spaces so that each word is separated by a single blank space only. Print message for invalid input.

I have written an answer this but cant made it. here's my code:

package OMG;
import java.util.Scanner;
public class Trimmer_new 
{
    String Trim(String s)
    {
        s=s.trim();
        String ans="";
        int k=0;
        s=s+" ";
        for(int i=1;i<=s.length();i++)
        {
            if(s.charAt(k)!= ' ') 
            {
                char g=s.charAt(k);
                ans=ans+g;
                k++;
            }
            else
            {
                while(s.charAt(k)==' ')
                {
                    k++;                    
                }
                ans=ans+" ";
                k++;
            }
        }
        ans.trim();
        return ans;
    }
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a sentance ending only with '!' or '?': ");
        String a=sc.next();  
        if(a.endsWith("!")==true||a.endsWith("?")==false)           
        {
            Trimmer_new ob= new Trimmer_new();
            System.out.println("Trimmed sentence: "+ob.Trim(a));
        }  
        else
        {
            System.out.println("error");
        }
        sc.close();
    }
}

But at time of running it throws an exception:

Please click here to see

Can anyone provide me with a better and clean code??

(I am doing this in Eclipse IDE)

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • 1
    Please post code and error as text instead of image. – seenukarthi May 25 '21 at 05:23
  • What was the input that caused this error? – Yoshikage Kira May 25 '21 at 05:24
  • 4
    In Java valid indices in strings (and arrays) range from 0 to length-1, but your code uses indices from 1 to length. – Thomas Kläger May 25 '21 at 05:24
  • @Goion the input is in the screen capture in the question. – Abra May 25 '21 at 05:26
  • You have a for loop with loop variable 'i'. But you don't use 'i'. Instead you use 'k'. Your Index Out Bounds Exception may caused by this. In order to separate words, you can use String.split. A double space results in an empty word, which you can remove. Then you can join the list again with an string joiner. https://docs.oracle.com/javase/8/docs/api/java/lang/String.html – Maik May 25 '21 at 05:29

1 Answers1

0

there are two issues. first you are never making check while incrementing K++ second you are not using i even you cant use i value as i=s.length(); you always need to use till -1 because array starts from 0.

better option is:

String result = Arrays.stream(input.split(" ")).filter(p-> p.length()>0).map(p-> p.trim()).collect(Collectors.joining(" "));