【发布时间】:2013-10-08 07:35:59
【问题描述】:
我是 java 新手,我的班级需要编写一个程序,用户在其中输入 XXXXXXXXX 形式的社会保障代码,并以 XXXX-XX-XXX 的形式返回。 例如,如果代码是 123456789,它将作为 123-45-6789 返回给他们。
这就是我所拥有的,我想使用子字符串来完成它。
导入 java.util.Scanner;
public class HWSocialSecuritySh {
public static void main (String [] args) {
Scanner reader = new Scanner (System.in);
String name;
int ssn;
System.out.print ("Enter nine digit social security number without dashes: ");
ssn= reader.nextInt();
System.out.print("Your formatted social security number is: ");
System.out.println(snn.substring(,) );
}
}
这是新代码
导入 java.util.Scanner;
public class HWSocialSecuritySH {
public static void main (String [] args) {
Scanner reader = new Scanner (System.in);
String name;
String Ssn="ssn";
System.out.print ("Enter nine digit social security number without dashes: ");
Ssn= reader.nextLine();
System.out.print("Your formatted social security number is: ");
System.out.println (Snn.substring(0,3) +"-"snn.substring(4,6) + "-"snn.substring(7,9);
}
}
【问题讨论】:
-
您为什么将社会安全号码读取为整数?您想对其进行格式化(而不是对其进行计算),因此不妨将其作为字符串读取。
-
你知道字符串连接吗?你可以写“a”+“b”,它会以字符串形式返回“ab”。类似地,如果字符串 a = "a",并且字符串 b = "b",则字符串 c = a + b 将使字符串 c 为 "ab"。在我看来,如果您理解这一点以及 String 类的
charAt()方法,那么这个问题的其余部分是微不足道的。 -
@Kon ya 我知道,那你具体怎么改,请用真实的代码形式写出来,而不是解释它。