gpt4 book ai didi

java - 编译器要么跳过 for 循环,要么不运行内部代码 (Java)

转载 作者:行者123 更新时间:2023-11-30 08:55:51 25 4
gpt4 key购买 nike

我正在尝试用 Java 编写代码来获取单词并对其进行打乱。我有一个 for 循环来遍历单词:

        String inWord = getWord.nextLine();

//loop as many times as x < length of word
for(int x = 0; x >= inWord.length(); x++){

//random number between 0 and length of word - 1
int randomChar = randChar.nextInt(inWord.length() - 1);

out.print("in the first for loop, randomChar is equal to " + randomChar + ", and x is equal to " + x);

循环继续执行一些其他不相关的代码,然后结束。然而,在运行时,控制台只接受一个词作为输入然后终止程序。没有打印任何内容。我的 for 循环有问题吗?

最佳答案

你已经切换了循环条件,它应该是:

for (int x = 0; x < inWord.length(); x++) {

注意循环的第二部分,这里是x < inWord.length()循环应该运行的条件,而不是循环应该中断的时间。只要该条件为 true,循环就会运行.


此外,

int randomChar = randChar.nextInt(inWord.length() - 1);

应该是:

int randomChar = randChar.nextInt(inWord.length());

否则你将没有机会返回字符串中的最后一个字符。

Random.nextInt(int bound)文档说:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

关于java - 编译器要么跳过 for 循环,要么不运行内部代码 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com