黑马程序员技术交流社区
标题:
一个小问题,求大神帮我剔除错误
[打印本页]
作者:
love~陌
时间:
2014-6-2 19:14
标题:
一个小问题,求大神帮我剔除错误
package wangkang;
import java.util.Arrays;
import java.util.Scanner;
public class Test3 {
/*
* 3、 从键盘接受一个数字,列出该数字的中文表示格式,
* 例如:键盘输入123,打印出一二三;键盘输入3103,打印出三一零三。
* */
public static void main(String[] args) {
Scanner s=null;
Long l=null;;
char[] ch=null;
try {
s=new Scanner(System.in);
l=s.nextLong();
ch=l.toString().toCharArray();
System.out.println(Arrays.toString(ch));
//程序在这之前都是正确的,数组遍历的时候就没结果了
for (int i = 0; i < ch.length; i++) {
caseChinese(ch[i]);
}
} catch (Exception e) {
System.out.println("输入错误!");
}
}
public static void caseChinese(int c){
switch(c){
case 0:
System.out.print("零");
break;
case 1:
System.out.print("一");
break;
case 2:
System.out.print("二");
break;
case 3:
System.out.print("三");
break;
case 4:
System.out.print("四");
break;
case 5:
System.out.print("五");
break;
case 6:
System.out.print("六");
break;
case 7:
System.out.print("七");
break;
case 8:
System.out.print("八"); ;
break;
case 9:
System.out.print("九");
break;
}
}
}
复制代码
我觉得下面封装的caseChinese方法可以换成返回值类型为String,这个希望大神帮我完成;
我的第二个问题就是希望大神依照现有封装的caseChinese方法来修改我主函数里面的代码
跪谢!!!!!!!!!!!!
作者:
123_yaya
时间:
2014-6-2 19:27
Switch的返回类型要是为String的话,是Jdk1.7版本新支持的功能哦,jdk1.6版本Switch支持返回类型是byte、char、short、int、枚举。楼主的Jdk是什么版本的
作者:
Boiled_Water
时间:
2014-6-2 19:33
把CASE语句里的数字加个单引号 '' 即可,因为你得到的字符数组与CASE里的数字不对应,加上单引号就能解决了
作者:
ゞ导火索゛
时间:
2014-6-2 22:55
本帖最后由 ゞ导火索゛ 于 2014-6-2 22:57 编辑
toCharArray()是转换成字符数组,所以你的caseChinese(int c)应该换成 caseChinese(char c), 然后case中每个数字用单引号括起来 表示是字符‘0’
作者:
波涛
时间:
2014-6-3 00:07
先回答第二个问题:首先你的代码是ok的,唯一注意的一点是你在调用caseChinese函数时传递进的参数不是int,你把你的这句 话 caseChinese(Integer.parseInt(ch
+""));改成: caseChinese(Integer.parseInt(ch
+"")); 就ok了。
再回答你的第一个问题:针对这个需求,没必要写的那个复杂,像下面这就可以的:【仅供参考】
import java.io.*;
public class Test3 {
public static void main(String[] args) throws IOException {
System.out.println("请输入一串数字:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
System.out.println(caseChinese(input));;
}
public static String caseChinese(String in)
{
char []str4China = {'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};
StringBuilder sb = new StringBuilder();
for(int i=0; i<in.length(); i++){
int a=Integer.parseInt(in.charAt(i)+"");
sb.append(str4China[a]);
}
return sb.toString();
}
}
复制代码
作者:
superob123
时间:
2014-6-3 00:37
123_yaya 发表于 2014-6-2 19:27
Switch的返回类型要是为String的话,是Jdk1.7版本新支持的功能哦,jdk1.6版本Switch支持返回类型是byte、ch ...
原来还可以这样
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2