Paul
Paul

Reputation: 13

Java returns impossible random numbers

Here is the code:

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

class string
{           
    public static void main(String[] args)
    {
        try
        {
        boolean go = true;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringBuffer inp = new StringBuffer(br.readLine());
        System.out.println(inp.reverse());
        inp.reverse();
        int leng = inp.length();
        inp.setLength(leng+100);
        int x = 0;
        StringBuffer res = inp;
        William bill = new William();
        res=bill.will(x+1, leng, res);
        while(x<leng-1 && go)
        {
            if(inp.charAt(x)==' ' && go)
            {
                res=bill.will(x+1, leng, res);
                go = bill.bob();

            }
        x=x+1;
        }
        System.out.println(res);
        }
        catch (IOException uhoh)
        {
            System.out.println("You entered something wrong.");
            System.exit(1);
        }
    }
}
class William
{
    public boolean go;
    public William()
    {
        this.go=true;
    }
    public StringBuffer will(int start, int len, StringBuffer input)
    {
        char cur = input.charAt(start-1);
        input.delete(start-1, start-1);
        int x = start;
        boolean happy=true;
        while(x<len && happy)
        {

            if(x==len-2)
            {
                this.go=false;
                input.insert(cur, x+1);
                x=x+2;
                happy=false;
            }
            else if(input.charAt(x)==' ')
            {
                input.insert(cur, x);
                x=x+1;
                happy=false;
            }
            else
            {
            x=x+1;
            }
        }
        return input;
    }
    public boolean bob()
    {
        return this.go;
    }

}

It is supposed to return the reverse of the input (it does that without error) and the input in an altered form of pig latin. tI houlds ookl ikel hist ("It should look like this"). But instead, it returns the original StringBuffer with a bunch of random numbers on the end. Two notable patterns in the error include the increase in the numbers as the number of letters increases, as well as overflow errors when short strings are inputted.

Upvotes: 1

Views: 145

Answers (2)

Nirmit Shah
Nirmit Shah

Reputation: 758

try input.insert(x+1, cur); instead of input.insert(cur, x+1); (and same for input.insert(cur, x))

Upvotes: 2

Lou Franco
Lou Franco

Reputation: 89172

You have the arguments to StringBuffer.insert() backwards. It's (offset, char)

Upvotes: 7

Related Questions