我想从字符串中提取最后四位数,并将其视为邮政编码。
此代码将接收用户输入,检查最后四个字符是否为数字。
如果是,请将其解压缩并在屏幕上显示。 如果不是,则返回错误。
现在,我想我可以提取它,但我不知道如何用格式显示它(我不能简单地覆盖toString()方法,因为我的项目中的许多其他部分需要格式化显示,而每个使用不同的格式。)
另外,为什么代码会生成多个输出,而不是一个?
以下是代码:
public static void main(String[] args) {
String address;
Scanner scn = new Scanner(System.in);
address = scn.next();
address=address.trim();
String postcode = "1234";
//this part extract postcode for further process.
for(int count=1;count<5;count++)
{
if(Character.isDigit(address.toCharArray()[address.length()-count]))
{
String[] split = postcode.split(address);
System.out.format("%s %s %n", "PO is: ", split);
}
else
{
System.out.println("PO invalid!");
System.exit(0);
}
}
}
一个可能的输出是:
qweqwr2132
PO是:[Ljava.lang.String; @ a46701
PO是:[Ljava.lang.String; @ 166a22b
PO是:[Ljava.lang.String; @ 120cc56
PO是:[Ljava.lang.String; @ 47393f
如果我最后有1位数,输出将显示一次。如果我有2位数,将显示两次。如果最后有4个或更多数字,输出最多可显示4次。
我意识到 if 部分肯定有问题,但我不知道为什么。
感谢您的耐心等待。
答案 0 :(得分:3)
我采取了不同的方法来解决你的问题。
public static void main(String[] args) {
String address;
Scanner scn = new Scanner(System.in);
address = scn.next();
address=address.trim();
String postcode = "";
if(address.length() < 4) {
System.out.println("The address is less that four characters long.");
} else {
postcode = address.substring(address.length() - 4);
try {
int code = Integer.parseInt(postcode);
System.out.println("The post code is :" + code);
} catch(NumberFormatException ex) {
System.out.println("ERROR");
}
}
}
答案 1 :(得分:1)
如何使用String.substring()?
final int ZIPLENGTH = 4;
String input = "qweqwr2132";
String zipCode = input.substring(input.length - ZIPLENGTH);
try {
Integer.parseInt( zipCode );
System.out.println("PO is: " + zipCode);
}
catch( Exception e ) {
System.err.println("Last 4 chars are not a number");
}
答案 2 :(得分:0)
试试这个:
String address;
Scanner scn = new Scanner(System.in);
address = scn.next();
address=address.trim();
String postcode = "1234";
//this part extract postcode for further process.
for(int count=4;count>0;count--)
{
if(Character.isDigit(address.toCharArray()[address.length()-count]))
{
System.out.format("%s %s %n", "PO is: ", address.toCharArray()[address.length()-count]);
}
else
{
System.out.println("PO invalid!");
System.exit(0);
}
}
答案 3 :(得分:0)
我的代码基于您的想法,否则这是工作代码:
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
public static void main(String []args){
String postcode;
String address;
Scanner scn = new Scanner(System.in);
address = scn.next();
address=address.trim();
if(address.length() > 3)
{
String testPostCode = address.substring(address.length() - 4, address.length());
if(isIntegerParseInt(testPostCode))
{
postcode = testPostCode;
System.out.println("postcode:" + postcode);
}
else
{
System.out.println("there is not valide address.");
}
}
}