建议,编写社会保障代码 [英] Advice, writing a social security code
问题描述
我是 Java 新手,我们需要编写一个程序,用户以 XXXXXXXXX 的形式输入社会保障代码,并以 XXXX-XX-XXX 的形式返回.例如,如果代码是 123456789,它将作为 123-45-6789 返回给他们.
Im new to java and my class we need to write a program where the user inputs there social security code in the form of XXXXXXXXX and it returns it in the form of XXXX-XX-XXX. For example if there code was 123456789 it would be returned to them as 123-45-6789.
这是我所拥有的,我想使用子字符串来完成它.
Here is what I have, I would like to use substrings to finish it off.
导入 java.util.Scanner;
import 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;
import 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);
}
}
推荐答案
实际上更合适的方法是使用 Matcher
带有 Pattern
代表一个 regex 包含社会保险号的子组作为 捕获组:
Actually a more appropriate way to do this would be to use a Matcher
with a Pattern
representing a regex containing the subgroups of the social security number as capturing groups:
final Pattern ssnFormat = Pattern.compile("^(\\d{3})(\\d{2})(\\d{4})$");
Matcher m = ssnFormat.matcher(ssn); // make ssn a string!
if (m.find()) {
System.out.printf("%s-%s-%s%n", m.group(1), m.group(2), m.group(3));
} else {
System.err.println("Enter a valid social security number!");
}
如前所述,社会保险号虽然可以表示为整数,但实际上是一串数字:作为数字没有意义.因此,您应该将其存储为 String
而 not 存储为 int
.
As noted, a social security number, while representable as an integer, is really a string of digits: it's meaningless as a number. Therefore, you should store it as a String
and not as an int
.
现在,在您的新代码中,您几乎完成了,但仍有一些问题:
Now, in your new code, you're almost there, but still have a few issues:
- 是
String
,不是string
. - 既然
ssn
是一个字符串,你不能将它分配给reader.nextInt()
的结果,因为它返回一个int代码>.相反,您需要使用
reader.nextLine()
. - 第二次和第三次
substring()
调用的范围略有偏离.参考方法的文档.
- It's
String
, notstring
. - Now that
ssn
is a string, you can't assign it to the result ofreader.nextInt()
, since that returns anint
. Instead, you'll want to usereader.nextLine()
. - The ranges of the second and third
substring()
calls are slightly off. Refer to the method's documentation.
这篇关于建议,编写社会保障代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!