1

I am beginner in Java & I am assigned with a lot of programs for my project this week. However, this one is confusing me for a long time now. I wrote a code for it but it is not displaying any result. There are no syntax errors btw! Have a look- Thank You!

import java.util.*;
import java.lang.*;

public class primeWord_reverser
{

    public static void main(String[] args) 
    {
       Scanner sc = new Scanner(System.in);
       int i,p,flag=0;

       System.out.println("Enter the sentence:");
       String SEN=sc.next();                                                                                                                                                                                                                                                                                                                      
       SEN=SEN.toUpperCase();
       SEN=SEN+" ";

       int L=SEN.length();

       StringBuilder fnalS= new StringBuilder("");
       StringBuilder finalS=new StringBuilder("");
       for(i=0;i<L-1;i++)
       {
           char chr=SEN.charAt(i);
           if (chr!=' ')
             {
                  fnalS.insert(fnalS.length(),chr);
             }
           else if(chr==' ')
             {
                 int LfnalS=fnalS.length();
                 int m=LfnalS/2;

                 for(p=2;p<=m;p++)
                 {    
                     if(LfnalS%p==0)
                      {        
                        flag++;
                      }    
                 } 

                 if(flag==0)    
                      {
                         fnalS.reverse();
                         finalS.append(" "+fnalS); 
                      }

                  else if(flag>0)
                      {
                         finalS.append(" "+fnalS);
                      }  
                   fnalS=new StringBuilder("");
                   flag=0;
              }       
       }
       System.out.println("the sentence is: "+finalS);
    }
}
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
user58736
  • 9
  • 8

1 Answers1

1

Try to change your code of:

String SEN = sc.next();

to

String SEN = sc.nextLine();

and remove -1 on your for loop:

for(i=0;i<L-1;i++)

to

for(i=0;i<L;i++)
msagala25
  • 1,806
  • 2
  • 17
  • 24