Java 用户名密码数组替换为星号

标签 java arrays string-formatting

所以我正在为学校编写一个处理用户名和密码的程序。它应该提示输入 3 个用户的用户名和密码。然后显示用户名和密码长度的星号。我几乎拥有所需的一切,包括如何在同一行上打印密码长度的星号:

//int asterix =password[x].length();
 * for (int y=0; y<asterix ;y++){
 *                  System.out.print("*");
 *              }
 */

我的问题是我需要像这样格式化输出:

USER ID                 PASSWORD

howdyDoodie              ***********
batMan                   ************
barneyRubble             ************

到目前为止,我的代码如下所示:

  public class test{

    /**
     * 
     * @param args
     */





    public static void main(String[] args){
        String[] user = new String[3];
        String[] password = new String[3];

        // Prompt for Username and Password and loop 3 times adding to next value in array
        for(int x=0; x<=2;x++){

        user[x] = JOptionPane.showInputDialog(null,"Enter Username: ");
        password[x] = JOptionPane.showInputDialog(null,"Enter Password: ");
        // Test number of loops
        //System.out.println(x);

        }

        //Field Names Print

        System.out.printf("\n%s\t%10s","Username","Password");

        for(int x=0; x<=2;x++){
            System.out.printf("\n%s\t%15s",user[x],password[x]);

        }

     System.exit(0);

    }
    /*
     * //int asterix =password[x].length();
     * for (int y=0; y<asterix ;y++){
     *                  System.out.print("*");
     *              }
     */

} // End of Class

我不知道如何打印星号并使用格式。

最佳答案

您需要一个嵌套循环。将打印星号 (*) 的 for 循环移动到打印所有用户的用户名和密码的 for 循环内。

你的循环应该是这样的。它未经测试,但您可以解决它以获得所需的输出。

System.out.printf("%-20s\t%-10s","Username","Password");

for(int x=0; x<=2;x++) {

     System.out.printf("%-20s\t",user[x]);  // Just print user here

     int asterix =password[x].length();
     for (int y=0; y<asterix ;y++){  // For the length of password 
         System.out.print("*");      // Print *
     }
     System.out.println();   // Print newline to move to the next line
}

%-20s\t 表示username需要20个空格,左对齐,并在后面添加一个制表符。

关于Java 用户名密码数组替换为星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13411087/

相关文章:

c# - 用中间的文本格式化 DateTime

java - 如何修复碰撞响应中的圆形和矩形重叠?

c++ - 我可以有一个跳过索引的一维 bool 数组吗?

c - 在 C 套接字上接收整数数组的最佳方法

javascript - 使用 Google Assistant 从 Firebase 返回数据数组

python - 如何使用 unicode emdash 进行字符串格式化?

c++ - 将double转换为wstring,但wstring必须用科学计数法格式化

java - 添加背景图像到 JPanel

java - 如何告诉 Maven 使用最新版本的依赖项?

java - OSGI 包的命令行参数和 JVM 参数