TheNotoriousWMB
TheNotoriousWMB

Reputation: 139

While loop using standard input

I'm trying to read in an indeterminate amount of chars into my data structure using readChar() from algs4 StdIn.java. Amount of lines of possible input is also unknown and spaces/tabs should be disregarded.

For example, sample input

ABC D
EF

Should be read as

ABDCEF

into my structure.

I'm having a lot of trouble finding an appropriate loop(s) to get StdIn to act how I want it to and not get me stuck in an infinite loop.

Upvotes: 0

Views: 2737

Answers (2)

triadiktyo
triadiktyo

Reputation: 479

After typing your input you will have to hit Ctrl-Z (at least on windows running in eclipse) to tell the StdIn class that there is no more input

    StringBuilder sb = new StringBuilder();
    char c;
    while (StdIn.hasNextChar()) {
        c = StdIn.readChar();
        if (c != '\n' && c != '\r' && c != ' ') { // plus add the unicode whitespace characters mentioned in the top comment
            sb.append(c);
        }
    }

    System.out.println(sb.toString());

Upvotes: 1

Randy
Randy

Reputation: 809

The file gives you quite a bit of that. Just use the readAllLines and then combine them into one line via StringBuffer.append(). So you iterate over each line, then iterate over each charater in each line. If it is not a space, append it to the StringBuffer. At the end print out the toString of StringBuffer(). The code has provisions to take care of newlines (\n) and returns (\r).

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    String[] lines = StdIn.readAllLines();
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        char[] charArray = line.toCharArray();
        for (int j = 0; j < charArray.length; j++) {
            char c = charArray[j];
            if (c != ' '){
                sb.append(c);
            }
        }
    }
    System.out.println(sb.toString());
}

Ran it with:

ABC DEF 
XYZ

It output:

ABCDEFXYZ

Upvotes: 1

Related Questions