我制作了一个成功的洗牌程序,该程序在运行时将这副牌的数量作为用户输入,并将每张牌打印在输出文本文件中的单独行上。
我想改进一下,如果这副牌有 10 到 99 张牌,文件会将包含数字 1 到 9 的行输出为 01 到 09。
我尝试阅读https://javadevnotes.com/java-integer-to-fixed-length-string并将其适应我的程序。它在 Jgrasp IDE 上编译成功,但在运行时输入牌中卡片的数量然后输出文件名后,程序因非法格式转换异常而终止:
currentCard= String.format("%0"+ deckLimit.length() + "d", String.valueOf(tempValue));
如何解决才能避免这种情况发生?
相关变量:
String currentCard;
int tempValue;
int deckSize;
String deckLimit;
deckSize = read.nextInt();
deckLimit = String.valueOf(deckSize);
问题线:
currentCard= String.format("%0"+ deckLimit.length() + "d", String.valueOf(tempValue));
最佳答案
您正在使用 %d
格式说明符,但您尝试使用它格式化的值 String.valueOf(tempValue)
是一个 字符串
。如果 tempValue
是您想要格式化的数字,则
currentCard= String.format("%0"+ deckLimit.length() + "d", tempValue);
是你想要的代码。
关于Java文件输出: Number formatting error for a card deck with number of cards only known at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60680810/