请帮助,我正在尝试编写一个程序,该程序读取书籍的库存文件并生成写入屏幕的库存报告。我在尝试格式化ISBN号时遇到问题。输入文件中的ISBN以10位数序列给出(例如:0321479270)。对于报告,我需要用1-3-5-1位数字(Ex 0-321-479270)重新格式化。
这是我到目前为止所拥有的......
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Inventory
{
public static void main(String[] args)throws IOException
{
//Vaiable declartions
int edition, quanity;
double pricePerBook;
String isbn, author, title, publisher;
//Open the file and set delimiters
File file = new File("inventory.txt");
Scanner inputFile = new Scanner(file);
inputFile.useDelimiter("_|/|\\r?\\n");
//Read from the file
while (inputFile.hasNext())
{
isbn = inputFile.next();
author = inputFile.next();
title = inputFile.next();
edition = inputFile.nextInt();
publisher = inputFile.next();
quanity = inputFile.nextInt();
pricePerBook = inputFile.nextDouble();
System.out.printf("%s" /* %s %s %d %s %d %f "*/, formatISBN(isbn)); //, author, title, edition, publisher, quanity, pricePerBook);
}
//Close the flie
inputFile.close();
}
//ISBN Method
public static String formatISBN(String isbn)
{
if (isbn.length() == 1)
{
isbn += -;
return isbn;
}
}
}
所以我在ISBN方法上遇到了麻烦,我似乎无法弄清楚如何用“ - ”打印ISBN。任何帮助将非常感激。
答案 0 :(得分:1)
您可以使用正则表达式:
return isbn.replaceAll("(\\d)(\\d{3})(\\d{5})(\\d)", "$1-$2-$3-$4");
答案 1 :(得分:0)
提取子字符串最简单:
return String.format("%s-%s-%s-%s",
isbn.substring(0, 0 + 1),
isbn.substring(1, 1 + 3),
isbn.substring(4, 4 + 5),
isbn.substring(9, 9 + 1));
答案 2 :(得分:0)
或使用StringBuilder:
StringBuilder result = new StringBuilder();
StringBuilder stringBuilder = new StringBuilder("0321479270");
result.append(stringBuilder.charAt(0));
result.append("-");
result.append(stringBuilder.substring(1,3));
result.append("-");
result.append(stringBuilder.substring(4));
return result.toString();
请记住,这仅适用于isbn格式正确的情况。