-4

Runtime Error: Runtime ErrorException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:658) at GFG.main(File.java:32)

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

class GFG {
 public static void main(String args[]) throws IOException
 {
  Scanner sc=new Scanner(System.in);
  int t=sc.nextInt();
  while(t-- > 0)
  { 
   String str=sc.nextLine();
   char c='\n';
   int i;
   for(i=0;i<str.length()-1;i++)
   {
    c=str.charAt(i);
    if(c>=97&&c<=122)
    {
     if(i==0)
      System.out.print((char)(c-32));
     else if(i!=0&&str.charAt(i+1)==' '&&str.charAt(i-1)==' ')
      System.out.print((char)(c-32));
     else if(i!=0&&str.charAt(i+1)!=' '&&str.charAt(i-1)==' ')
      System.out.print((char)(c-32));
     else
      System.out.print(c);
    }
    else
     System.out.print(c);
   }
          c=str.charAt(i);
   if(c>=97&&c<=122)
    System.out.println((char)(c-32));
   else
    System.out.println(c);
    
  }   
 }
}

2 Answers2

0

its calling a place in string that does not exist with what it seems str.charAt(i-1) method call. When i == 0, or i == str.length-1 and call charAt(i+1). You can always put a break point and debug your application through IDE.

also Exception tells you it's location : GFG.main(File.java:32) thats 32nd line Which is that line in the original file with all the imports, comments and package name?

Zeta Reticuli
  • 311
  • 2
  • 13
0

The problem is with your Scanner class method. If you want to use nextLine after nextInt, you have to fire one blank newline in your code like,

sc.nextLine();

Then the scanner will scan your String str=sc.nextLine();.

Coming to your exception, when the scanner will take input, it is taking as a blank string like "", so when your trying to find chatAt(0), which will trying to excess the value from the empty String.

So put the below code in your program,

sc.nextLine(); // just for scanner to skip this line
String str=sc.nextLine();

For more infor, you can refer this link Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?

Arvind Katte
  • 845
  • 2
  • 11
  • 18