对do-while循环的困惑

时间:2017-04-15 05:20:25

标签: java

这是我的代码

import java.util.*;
public class dowhile
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();

     String hash = "#";

     do
     {
        System.out.println(hash);
        hash = hash + 1;
        } while (hash.equals(5));
     }
}

我对如何在用户询问后显示的数量感到困惑。

我知道hash.equals(5)没有意义。 我该如何修复此代码?

任何人请向我提出建议。

4 个答案:

答案 0 :(得分:0)

在循环之前声明一个int变量。将数字增加1,然后检查while循环中的数字将打印所需的输出。

 int i=0;
 do
 {
    System.out.println(hash);
    i=i + 1;
 } while (i<tim);

答案 1 :(得分:0)

您可以使用tim作为计数器,并在测试之前减少,如果它大于0。像,

int tim = kb.nextInt();
do {
    System.out.print("#");
} while (--tim > 0);
System.out.println();

答案 2 :(得分:0)

您还可以使用具有StringUtils.repeat(String, int)

的Apache commons-lang3

<强>参数: str - 要重复的String,可以为null repeat - 重复str的次数,Negative被视为零

答案 3 :(得分:0)

hash是您要打印的字符串,因此您不应该像这样更改其值:

hash = hash + 1; // this does not actually compile anyway.

要跟踪仍需要打印的次数,您需要一个int变量。如您所见,timint,它已经存储了用户输入。我们使用tim作为我们的计数器。

每次打印#时,您将tim减少1.在循环条件下,您可以编写tim > 0。只要tim大于0,这将使循环运行。

Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();

String hash = "#";

do {
    System.out.println(hash);
    tim--; // this is equivalent to tim = tim - 1;, in case you did not know
} while (tim > 0);

但是,我不认为在这里使用do-while循环是合适的。如果用户输入0怎么办?仍然会打印一个#。那不是好事吗?

我建议在这里使用for循环:

Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();

String hash = "#";

for (int i = 0 ; i < tim ; i++) {
    System.out.println(hash);
}
相关问题