【问题标题】:how to duplicatea char variable using a for loop [duplicate]如何使用 for 循环复制 char 变量[重复]
【发布时间】:2016-03-18 22:22:20
【问题描述】:

所以我想知道如何使用 for 循环复制字母 c。我已经使用 * 符号完成了此操作,但似乎无法使其与字母 c 一起使用。我使用 IBIO 来获取输入。我需要知道如何以与 *.当我运行代码时, c 只打印一次。为什么是这样?请帮我解决它。

 public class Methods
 {
     public static void main (String args[])
    {
        new Methods ();
    }


    public quadMethods ()
    {
        printNStars (5);
        printNChars (6, 'q');

    }


    public void printNStars (int n)
    { //prints 'n' stars on the screen in a row
    n = IBIO.inputInt ("Enter a number for 'n': ");
    for (int i = 0; i <= n; i++)
     System.out.print ("*");
    System.out.println ("");
    }


    public void printNChars (int n, char c)
    { //prints 'n' of character c on the screen in a row
    for (int i = 0; i <= n; i++);
    {
     System.out.print ("c");
    }
    System.out.println ("");
    }
}

【问题讨论】:

  • 这是在for循环之后由流氓;引起的。
  • for (int i = 0; i &lt;= n; i++) 更改为 for (int i = 0; i &lt;= n; i++){
  • 这个问题是由无法再复制的问题或简单的印刷错误引起的。虽然类似的问题可能是这里的主题,但这个问题的解决方式不太可能帮助未来的读者。这通常可以通过在发布之前确定并仔细检查重现问题所需的最短程序来避免。

标签: java loops for-loop character


【解决方案1】:

您有几个问题。一个是两个循环的迭代次数:

public void printNStars (int n)
{
    n = IBIO.inputInt ("Enter a number for 'n': ");
    for (int i = 0; i <= n; i++)
        System.out.print ("*");
    System.out.println ("");
}

这将输入一个数字并打印n+1 星星。您可能打算这样做:

public void printNStars (int n)
{
    for (int i = 0; i < n; i++)
        System.out.print ("*");
    System.out.println ("");
}

第二个问题是你其他循环中的分号:

for (int i = 0; i <= n; i++);

这会创建一个什么都不做的循环。输出语句也输出cs,而不是传入的字符!

第二个功能应该是:

public void printNChars (int n, char c)
{
    for (int i = 0; i < n; i++)
    {
        System.out.print (c);
    }
    System.out.println ("");
}

【讨论】:

  • 感谢您的详细回答。但是,当我运行程序时,我只打印了 6 个 c。这是为什么呢?
  • 呃...因为你叫它,要求六个:printNChars (6, 'q');...?
  • 那我为什么不打印出来 5 星??
  • 如果你使用我修正后的printNStars 并称之为printNStars(5) 那么你应该得到五颗星
  • 没关系,再次感谢
猜你喜欢
  • 2020-04-05
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 2017-04-25
相关资源
最近更新 更多