0

I tried multiple versions, including several solutions found here on StackOverflow, but I always get numbers instead of the characters in the console. For a homework in my uni, we need to invert the characters in a string. But creating the new string seems to be not so easy.

I tried using a StringBuilder,

StringBuilder builder = new StringBuilder();
// ...
builder.append(c); // c of type char

String concatenation,

System.out.print("" + c); // c of type char

and even String.valueOf(),

System.out.print(String.valueOf(c)); // c of type char

and each of them again with explicit conversion to char. But I always get the ordinal number of the characters in a sequence instead of the actual characters as output in the console. How do I correctly build a new string from chars?

/**
 * Praktikum Informatik - IN0002
 * Arbeitsblatt 02 - Aufgabe 2.6 (Buchstaben invertieren)
 */

public class H0206 {

    public static String readLine() {
        final StringBuilder builder = new StringBuilder();
        try {
            // Read until a newline character was found.
            while (true) {
                int c = System.in.read();
                if (c == '\n')
                    break;
                builder.append(c);
            }
        }
        catch (java.io.IOException e) {
            ; // We assume that the end of the stream was reached.
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        // Read the first line from the terminal.
        final String input = readLine();

        // Create a lowercase and uppercase version of the line.
        final String lowercase = input.toLowerCase();
        final String uppercase = input.toUpperCase();

        // Convert the string on the fly and print it out.
        for (int i=0; i < input.length(); ++i) {
            // If the character is the same in the lowercase
            // version, we'll use the uppercase version instead.
            char c = input.charAt(i);
            if (lowercase.charAt(i) == c)
                c = uppercase.charAt(i);
            System.out.print(Character.toString(c));
        }
        System.out.println();
    }

}
Niklas R
  • 16,299
  • 28
  • 108
  • 203
  • 4
    `c` of type `char`? The one I see in your example is an `int`. Also, what does `System.in.read()` do? – Sotirios Delimanolis Oct 27 '14 at 15:36
  • [`String#valueOf()` shoud work](http://stackoverflow.com/questions/8172420/how-to-convert-a-char-to-a-string-in-java)... Are you sure you character is not a digit, e.g. `'4'`? – sp00m Oct 27 '14 at 15:38
  • `c` may held a character data but it is certainly of type `int` and not `char`. Convert it to `char` like this: `char ch = (char) c;`. – icza Oct 27 '14 at 15:40
  • @SotiriosDelimanolis Where is the `int`? I am trying to convert `c`, not `i`. `System.out.print(Character.toString(c));` -> c is a `char` here – Niklas R Oct 27 '14 at 15:40
  • 1
    @icza Ohhhh I searched for the problem in the wrong function. :) Thank you! I thought the problem was in main(), but its in readLine() – Niklas R Oct 27 '14 at 15:41

3 Answers3

2

The problem I see with the sample code you provided is here:

int c = System.in.read();
if (c == '\n')
   break;
builder.append(c);

The way you call the method, Stringbuilder.append(int) will be called. As the javadoc says, "the overall effect is exactly as if the argument were converted to a string by the method String.valueOf(int), and the characters of that string were then appended to this character sequence". Casting the integer-value to char like this will result in the desired behavior:

int c = System.in.read();
if (c == '\n')
   break;
builder.append((char) c);
0

Here is a sample how to invert a String, there is another options, i think this one is more didacticism

 public static void main(final String[] args) {
    String text = "This is a string that will be inverted";
    char[] charArray = text.toCharArray();
    char[] invertedCharArray = new char[charArray.length];
    for (int i = 1; i <= charArray.length; i++) {
        char c = charArray[charArray.length - i];
        invertedCharArray[i - 1] = c;
    }
    System.out.println(text);
    System.out.println(new String(invertedCharArray));
}
Leonardo Dias
  • 301
  • 2
  • 5
0
 try { // Read until a newline character was found.
        while (true) {
            int c = System.in.read();
            if (c == '\n') break;
            builder.append(c);
        }

From the sample you gave, I can see that this is causing the problem. Because you are reading the char input as an int, it converts the char to its ordinal value so it can be stored (and therefore used) as an integer.

In public final class StringBuilder you're calling append(int i), which returns int. If int c = System.out.read(); is required for this to be declared as an integer, you can cast c to a char.

char ch = (char)c;
builder.append(ch)

If needed, this leaves c as an integer and stores its "original value" (What it was before it was turned into an int, i.e. the key pressed) in a variable if needed. If you only need to add it to the string, without reusing it for any reason, you can cast c to a char directly with append((char) c).

Siyual
  • 16,415
  • 8
  • 44
  • 58
DarmaniLink
  • 126
  • 10