-1

我的 while 循环有问题。程序询问用户他们的姓名,在用户输入后,程序会询问您想打印多少次输入。

我已经被困在我的 while 循环上很长一段时间了,只有当我做类似的事情时才能让它工作:} while (antal > some random number)

package uppg2;

import java.util.Scanner;

public class Uppg2 {

    public static void main(String[] args) {

        Scanner name = new Scanner(System.in);
        Scanner ant = new Scanner(System.in);
        int antal;
        String namn;
        System.out.print("Whats your name?: ");
        namn = name.nextLine();

        System.out.print("How many times u wanna print ur name?: ");
        antal = ant.nextInt();
        do {

            System.out.print(namn);

        } while (????);
        antal++;
        namn = null;
        antal = 0;
    }
}
4

6 回答 6

3

我个人会像这样使用 for 循环:

for(int i = 0 ; i < antal; i++){
    System.out.println(namn);
}
于 2013-02-06T20:36:33.070 回答
2

您可以倒计时antal( antal--) 直到它为 1。但不确定是否可以销毁其中的值antal

于 2013-02-06T20:36:42.477 回答
2

就像其他人建议的那样,这将是 for 循环的用例。但是当你坚持使用 while 循环时:

int counter = 0; // a variable which counts how often the while loop has run

do {
    System.out.print( namn ); // do what you want to do
    counter++                 // increase the counter
} while (counter < antal)     // check if the desired number of iterations is reached

当循环结束时不再需要的值antal时,您也可以不使用计数器变量,只需减少每个循环的 antal 并检查它是否已达到 0。

do {
    System.out.print( namn );
    antal--;
} while (antal > 0)
于 2013-02-06T20:39:58.553 回答
1
package uppg2;

import java.util.Scanner;

public class Uppg2 {

public static void main(String[] args) {

    final Scanner in = new Scanner(System.in);
    int antal;
    String namn;
    System.out.print("Whats your name?: ");
    namn = in.nextLine();

    System.out.print("How many times u wanna print ur name?: ");
    antal = in.nextInt();
    int i = 0;
    while(i < antal){

            System.out.print( namn );
            i++;

    }
    in.close();
}
}

告诉我这是否有效。基本上,您需要一个增量计数器来确保它只打印出所需的次数。由于我们从 0 开始计数,我们不需要确保它一直持续到它等于打印时间,但它仍然在它之下。

于 2013-02-06T20:36:54.077 回答
1

您必须有一个在 do-while 循环内递增的计数器,并与该值进行比较

它会使你的循环循环类似于:

antal = ant.nextInt();
int i = 0;
do{ 

            System.out.print( namn );
            i++; 

    }while (i < antal);

请注意,因为它是一个 do-while 循环,所以即使用户输入零,您也将始终至少打印一次名称。为防止这种情况,您需要使用 for 或 while 循环,如其他回答者所述,或在System.out.println调用周围使用 if 条件来检查 antal 是否为零。

另外,如果您不在乎最后是什么antal,则可以使用TofuBeer的解决方案。

于 2013-02-06T20:40:54.903 回答
0

这是类似问题的解决方案。看看您是否无法将其转化为您的问题:

// How many times to I want to do something?
int max = 40;
for (int i = 0; i < max; i++) {
    // Do something!
}
于 2013-02-06T20:35:28.387 回答