求助!一道关于I/O的问题
要求:在不使用容器的前提下,在命令行上输入一排阿拉伯数字,然后把这些数字转换为汉字,如:输入 "2003 ",转化为 "二零零三 "
下面是小弟自己写的代码,但得不到预想结果:
import java.io.*;
public class Test{
public static void main(String[]args) throws
IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String s=in.readLine(); //读取输入并将其转化为一个String
char[]a=s.toCharArray(); //将String转换为一个char型的array
String[]b=new String[]{ "零 ", "一 ", "二 ", "三 ", "四 ", "五 ", "六 ", "七 ", "八 ", "九 "};
for(int i=0;i <s.length();i++){ //判断a中元素的值并将值作下标赋给b数组
if(a[i]==0)System.out.print(b[0]);
if(a[i]==1)System.out.print(b[1]);
if(a[i]==2)System.out.print(b[2]);
if(a[i]==3)System.out.print(b[3]);
if(a[i]==4)System.out.print(b[4]);
if(a[i]==5)System.out.print(b[5]);
if(a[i]==6)System.out.print(b[6]);
if(a[i]==7)System.out.print(b[7]);
if(a[i]==8)System.out.print(b[8]);
if(a[i]==9)System.out.print(b[9]);
}
}
}
编译,运行都能通过,就是得不到预想结果
请各位大虾帮助,小弟感激不尽
------解决方案-------------------- if(a[i]== '0 ')System.out.print(b[0]);
if(a[i]== '1 ')System.out.print(b[1]);
if(a[i]== '2 ')System.out.print(b[2]);
if(a[i]== '3 ')System.out.print(b[3]);
if(a[i]== '4 ')System.out.print(b[4]);
if(a[i]== '5 ')System.out.print(b[5]);
if(a[i]== '6 ')System.out.print(b[6]);
if(a[i]== '7 ')System.out.print(b[7]);
if(a[i]== '8 ')System.out.print(b[8]);
if(a[i]== '9 ')System.out.print(b[9]);
这样就好了
------解决方案--------------------public class Test
{
public static void main(String[] args) throws Exception
{
while(true){
java.io.BufferedReader in=new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String s=in.readLine();
if(s.equals( "exit "))
System.exit(0);
System.out.println( "输入的内容为: "+s);
char[] a=s.toCharArray();
String[] b=new String[]{ "零 ", "一 ", "二 ", "三 ", "四 ", "五 ", "六 ", "七 ", "八 ", "九 "};
StringBuffer sb=new StringBuffer();
for(int i=0;i <s.length();i++)
{
sb.append(b[Integer.parseInt(Character.toString(a[i]))]);
}
System.out.println( "转换: "+sb.toString());
}
}
}