This is a homework assignment and I'm having trouble with my output. Everything works as expected except the Integer.toString() isn't giving me the result I want. It is still outputting just a bunch of numbers when I want them to be converted to the actual word. Here's the code and output:
import java.io.*;
public class NumStream extends OutputStream
{
public void write(int c) throws IOException
{
StringBuffer sb = new StringBuffer();
switch(c)
{
case ' ': sb.append(" ");
break;
case '1': sb.append("One");
break;
case '2': sb.append("Two");
break;
case '3': sb.append("Three");
break;
case '4': sb.append("Four");
break;
case '5': sb.append("Five");
break;
case '6': sb.append("Six");
break;
case '7': sb.append("Seven");
break;
case '8': sb.append("Eight");
break;
case '9': sb.append("Nine");
break;
case '0': sb.append("Zero");
break;
default: sb.append(Integer.toString(c));
break;
}
System.out.print(sb);
}
public static void main(String[] args)
{
NumStream ns = new NumStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(ns));
pw.println("123456789 and ! and # ");
pw.flush();
}
}
the output is: OneTwoThreeFourFiveSixSevenEightNine 97110100 33 97110100 35 1310
can somebody please tell me how to format code easier in this forum? I had to manually 8 space indent each line and there's got to be an easier way!
For characters that aren't digits, you're taking the character code and converting it to a number. So 97 110 and 100 are the character codes for 'a', 'n', and 'd' while 33 and 35 are !
and #
.
What you probably want for your default case is just:
default: sb.append((char)c); break;
Note that creating a new StringBuffer each time the write routine is called is extremely wasteful and inefficient. Since you're only ever appending one string/char to it, you might as well just print that string/char directly rather than copying through a StringBuffer.
您正在输出sb.append(Integer.toString(c))
中不是数字的字符的ASCII码。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.