我正在创建一个随机访问文件,用于存储玩家的姓名、排名和技能,并且我正在这样做,以便如果您输入的玩家姓名长度超过 26,则会在 26 处被删除,并且如果它比 26 短,我想用空格填充它。
我想出了 subString 以确保只选择前 26 个,但我想知道如果我没有输入任何值,你们会建议什么来确保我有 26 个填充的空白。这只是我的代码片段,如果您希望我添加更多内容,我会的。
public static String PlayerNameMethod (RandomAccessFile store){
try{
String PlayerName = input.next();
store.writeUTF(PlayerName);
if (PlayerName.length()> 26){
PlayerName.substring(0,26);
System.out.print("The Player Name is" + PlayerName);
}
if (PlayerName.length()< 26){
//PART I CANT FIGURE OUT
}
最佳答案
有很多方法可以做到这一点 - 最简单的一种是循环添加空格,直到字符串足够长。
但是代码非常短并使用内置函数的一种方法是 String.format
函数:
PlayerName = String.format("%-26s", PlayerName);
<小时/>
请注意,您的其余代码存在一些问题。该行:
PlayerName.substring(0,26);
没有做任何事情。字符串是不可变的,这意味着更改字符串的函数始终返回新字符串 - 它们不会修改原始字符串。
所以该行应该是:
PlayerName = PlayerName.substring(0,26);
关于java - 如果所需长度不够长,如何用空格填充字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38449854/