未检测到“空格”的ASCII编号

时间:2013-05-22 23:50:28

标签: java

简单密码制作者

Random myrand = new Random();
int x = myrand.nextInt(126);
x = x+1;
char c = (char)x;
//this gets the character version of x
for (int mycounter = 0; mycounter < 10; mycounter++)
{
  x = myrand.nextInt(127);
  x = x+1;
  if (x == 32)
  {
   x = 33;
  }
  c = (char)x;
  System.out.print(c);
  }
 System.out.println();

我的错误在哪里?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

目前您正在检测空格字符,但其他字符不可打印?我不希望任何低于ASCII 32的内容可用作密码。

我怀疑你想要这样的东西:

// Remove bit before the loop which used x and c. It was pointless.
Random myrand = new Random();
for (int mycounter = 0; mycounter < 10; mycounter++)
{
    // Range [33, 127)
    int x = myrand.nextInt(127 - 33) + 33;
    char c = (char) x;
    System.out.print(c);
}

上面的代码不是将“所有不可打印的”映射到单个字符,而是通过进一步限制范围来避免首先选择它。