Search code examples
javastringcharstringreader

How can I get the next char in my string with the stringreader in Java?


Consider this code:

public static void main (String[] args) {

    String name = "(My name is Bob)(I like computers)"

    StringReader s = new StringReader(name);

    try {
        // This is the for loop that I don't know 
        for () {
            String result = "";  
            // Here the char has to be appended to the String result.
        }
        System.out.println("The string is: " + result);

    } catch (Exception e) {
        e.toString();
    }
}

What I am looking for is a for-loop that first looks at the character at the current position and then appends it to a string if that character is not ")". However, the char ")" should also be appended to the string. In this example the output should be:

The string result is: (My name is Bob)


Solution

  • Below is a working solution.

    import java.io.StringReader;
    
    public class Re {
    public static void main (String[] args) {
    String name = "(My name is Bob)(I like computers)";
    
    StringReader s = new StringReader(name);
    
    try {
        // This is the for loop that I don't know
        String result = "";
        int c = s.read();
        for (;c!= ')';) {
            result = result + (char)c;
            // Here the char has to be appended to the String result.
            c = s.read();
        }
        result = result + ')';
        System.out.println("The string is: " + result);
    
    } catch (Exception e) {
        e.toString();
    }
    
    }
    }