-1
import java.util.Scanner;

class piglatin{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("enter a string");
        String s=in.nextLine(),n1="",n2="",n3="";
        int i;
        for(i=0;i<s.length();i++){
            if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='o'||s.charAt(i)=='i'||s.charAt(i)=='u')
                while (s.charAt(i)!=' '&& i!=s.length()){     // hre lies the problem
                    n1+=s.charAt(i);
                    i++;
                }
            else if(s.charAt(i)==' '){
                n2="";
                i++;
            }
            else
                n2+=s.charAt(i);

            n3=n3+n1+n2+"ay ";


        }
        System.out.println(n3);
    }
}

here when i matches the value of length the loop should break but it always show outofbounds exception. what is my mistake i have used && and the gateway should give false && true = false please help

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

3 Answers3

0

On your last iteration while (s.charAt(i)!=' '&& i!=s.length()){

It tries to grab s.charAt(i) causing an IndexOutOfBounds, because i = length meaning that is one value to high for the size of the array.

If you check the size first it will evaluate to be not true because i = length so you will never reach the s.charAt(i) because the first evaluation will not be true, thus never throwing the exception. This is called short circuiting.

Beez
  • 478
  • 9
  • 23
0

the fuses defining your condition are wrong!

if(s.charAt(i)=='a'|| s.charAt(i)=='e'|| 
   s.charAt(i)=='o'|| s.charAt(i)=='i'|| s.charAt(i)=='u')
       
    while (s.charAt(i) != ' ' && i!=s.length()){     // hre lies the problem
        n1+=s.charAt(i);
        i++;
    }

if the char is a or e, i, o or u then why check s.charAt(i) != ' '?? on the other hand, if you do a for like this

for(i=0;i<s.length();i++){ 

where i will never reach the s.length why do u do: i!=s.length()

that while condition is just dead code

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • In theory it could be a space, because he is incrementing in the array in the while loop so there could be different values that we don't know about. – Beez Aug 25 '20 at 17:39
  • nope... "IF is a vowel" is not possible to be a space... – ΦXocę 웃 Пepeúpa ツ Aug 25 '20 at 17:41
  • `while (i != s.length() &&s.charAt(i) !=' ')` length should be checked first. – Som Aug 25 '20 at 17:43
  • He only check the char at `i` is 'c' say it is at index 0, it goes into the loop which increments to the next `i` which would be index 1 since we can't see the array we don't know what the next value at the index is – Beez Aug 25 '20 at 17:44
0

Change your while condition to this :

while (i != s.length() && s.charAt(i) !=' ')

You should check the length first before charAt(i)

Som
  • 1,522
  • 1
  • 15
  • 48