我创建了一小段代码,只需使用随机数生成器对字符串进行加扰。当我使用netbeans运行程序时,一切正常。但是,如果我尝试从命令提示符运行.jar文件,则输出会出现乱码。它看起来似乎没有乱码,最后几个字母总是首先出现。其他时候它只是省略了部分字符串。
当我尝试使用字符串文字而不是使用命令行中的输入时,一切正常。所以我假设程序的输入部分存在问题。
这段代码位于主方法
中 while(true){
System.out.print("$");
Scanner s = new Scanner(System.in);
s.useDelimiter("\n");
String in = s.next();
String out = "";
if (in.startsWith("ks")) {
out = ScrambleString.keepSpaces(in.substring(3));
} else if (in.startsWith("fr")) {
out = ScrambleString.fullRandom(in.substring(3));
} else if (in.startsWith("kw")) {
out = ScrambleString.randomByWords(in.substring(3));
} else if (in.equals("exit")) {
break;
} else {
System.out.println(" Syntax: [fr:ks:kw] sentence\n fr full random \n ks keep spaces \n kw keep words");
}
System.out.println(">>" + out);
}
这些是从上面调用的静态函数
/**
* only ignore spaces while randomizing
*
* @param a
* @return
*/
public static String keepSpaces(String a) {
a = a.toLowerCase();
char[] s = a.toCharArray();
Random r = new Random();
for (int i = 0; i < s.length; i++) {
char t = s[i];
int num = r.nextInt(s.length);
if (s[i] != ' ' && s[num] != ' ') {
s[i] = s[num];
s[num] = t;
}
}
return String.valueOf(s);
}
/**
* randomize every char regardless of word or space
*
* @param a
* @return
*/
public static String fullRandom(String a) {
a = a.toLowerCase();
char[] s = a.toCharArray();
Random r = new Random();
for (int i = 0; i < s.length; i++) {
char t = s[i];
int num = r.nextInt(s.length);
s[i] = s[num];
s[num] = t;
}
return String.valueOf(s);
}
/**
* change the order of the characters per word. words are separated by spaces
*
* @param a
* @return
*/
public static String randomByWords(String a) {
String[] words = a.split(" ");
String out = "";
for (int i = 0; i < words.length; i++) {
out += fullRandom(words[i]) + " ";
}
return out;
}