我正在尝试在Java中编写一个非常小的程序,它接受一个字符串作为输入,并使用一个生成伪随机聊天函数的函数,并将它们与字符串的每个元素进行比较,如果它们是相同的,则将字符写入a结果数组与字符串代码中的索引相同,如下所示,
public static char randomChar(){ int diceroll = dice.nextInt(25); return alphabet.charAt(diceroll); } public static int itterator(String input){ char inputchar; //convert input string to array char[] stringarray = input.toCharArray(); while(stringarray != result) count++; //itterate each character for(int i = 0; i<input.length(); i++) { inputchar = input.charAt(i); if( randomChar() == inputchar ) { result[i] = inputchar; } } return count; }程序永远不会终止,这是因为我创建了一个无限循环还是有另一个原因? 任何帮助表示赞赏!
干杯
I'm trying to write a really small program in Java that takes a string as input and uses a function that generates a pseudo random chatacter and compares them to each element of the string, if they're the same the character gets written to a result array at the same index that it was in the string code is below,
public static char randomChar(){ int diceroll = dice.nextInt(25); return alphabet.charAt(diceroll); } public static int itterator(String input){ char inputchar; //convert input string to array char[] stringarray = input.toCharArray(); while(stringarray != result) count++; //itterate each character for(int i = 0; i<input.length(); i++) { inputchar = input.charAt(i); if( randomChar() == inputchar ) { result[i] = inputchar; } } return count; }The program never terminates however, is this because I have created an infinite loop or is there another reason? Any help is appreciated!
Cheers
最满意答案
你错过了while语句中的{} ,但这不是你将要遇到的唯一问题。
我假设result也是一个char数组,但我看不到你在代码中声明它的位置。 如果它是一个char数组,那么你无法使用stringarray != result来比较它,因为它总是为false,导致另一个无限循环。
你需要使用Arrays.equals(array1, array2); 为了在数组之间进行比较。
将您的while语句更改为:
while(!Arrays.equals(stringarray, result)) { //code here }而你将避免另一个无限循环。
You are missing the {} around your while statement, but that's not the only issue you're going to have.
I'm assuming that result is a char array too, but I can't see where you've declared it in your code. If it is a char array, then you cannot compare it using stringarray != result as it will always be false, causing another infinite loop.
You need to use Arrays.equals(array1, array2); in order to do a comparison between arrays.
Change your while statement to:
while(!Arrays.equals(stringarray, result)) { //code here }And you will avoid another infinite loop.
更多推荐
发布评论