场景一:要求用户输入5位数的输入编号和3位数的代码,然后在文件名和文件内部替换它们。
场景二:用户被要求输入5位数的输入数字AND,然后询问他们是否要输入/更改3位数的代码。如果是,那么他们可以输入一个3位数的代码
当前代码:
package blah blah
import all stuffs...
public class NumbChanger{
public static void main(String[] args) {
try {
Scanner user = new Scanner(System.in);
String inputCode= "";
System.out.print("Enter a xml file directory: "); // Enter xml file directory.
String directory = user.nextLine();
System.out.print("Enter the 5 digit starting Number: ");
int inputNumber = user.nextInt();
System.out.print("Do you want to change the code?");
boolean yesChange = user.hasNext();
if (!yesChange){
} else {
System.out.print("Enter the 3 character Code: ");
inputCode = user.next();
}
user.close();
Path folder = Paths.get(directory);
FilenameFilter xmlFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".xml")) {
return true;
} else {
return false;
}
}
};
//this is the list of files
File[] allFiles = folder.toFile().listFiles(xmlFilter);
if (allFiles == null) {
throw new IOException("No files found");
}
String fileName;
for(File aFile : allFiles) {
if (aFile.isFile()) {
fileName = aFile.getName();
String oldNumber = fileName.substring(
((fileName.lastIndexOf(".")) - 12), (fileName.lastIndexOf(".")) - 4);
String oldCode = fileName.substring(
((fileName.lastIndexOf(".")) - 3), (fileName.lastIndexOf(".")));
if (!yesChange){
} else {
inputCode = fileName.substring(
((fileName.lastIndexOf(".")) - 3), (fileName.lastIndexOf(".")));
}
String newNumber = String.valueOf(inputNumber++);
String newFileName = fileName.replaceAll(
oldNumber, newNumber);
if (!yesChange){
} else {
newFileName = newFileName.replaceAll(oldCode, inputCode);
}
//renaming the file
Path newFilePath = Files.move(aFile.toPath(),
aFile.toPath().resolveSibling(newFileName));
//replacing the entry # within the XML
String content = new String(Files.readAllBytes(newFilePath),
StandardCharsets.UTF_8);
content = content.replaceAll(oldNumber, newNumber);
content = content.replaceAll(oldCode, inputCode);
Files.write(newFilePath, content.getBytes(StandardCharsets.UTF_8));
}
}
System.out.print(allFiles.length + " xml files were changed.");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println(" Good Job!");
System.exit(0);
}
}
}
对上述代码的反思。
目前,如果他们同时输入两个值,我会使其工作。我哪里错了?
进一步增强:检查代码的长度。
我知道我可以做一个简单的
if (inputCode.length == 3){
}
else {
System.out.print ln ("Error")
}
但我不知道布尔和while循环,如果用户输入了不同的值,我希望他们再次提示,而不是再次运行程序。
提前感谢!:)
我不确定我是否理解你的问题,但不会吗
System.out.print("Enter the 5 digit starting Number: ");
int inputNumber = user.nextInt();
while(String.valueOf(inputNumber).length() != 5) {
System.out.println("Please enter a 5 digit number.");
inputNumber = user.nextInt();
}
做这份工作?如果数字不是5位数,则要求用户输入一个新数字。
不能在Integer上使用.length(),因此必须先将其转换为String。因此线路
String.valueOf(inputNumber).length()