无限循环问题,比较java中的数组(Infinite loop issue, comparing arrays in java)

系统教程 行业动态 更新时间:2024-06-14 16:57:17
无限循环问题,比较java中的数组(Infinite loop issue, comparing arrays in java)

我正在尝试在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.

更多推荐

本文发布于:2023-04-12 19:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a1131bedc410e7d7b09ca35777543fa6.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Infinite   java   loop   arrays

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!