【问题标题】:How to write text with parameter and variable如何使用参数和变量编写文本
【发布时间】:2016-09-18 00:59:19
【问题描述】:

有一个我想不出来的任务。作业是:

  1. 使用给定的方法:

    static void writeTexts(String text, int amount);
    

    根据变量数量给定的次数打印出参数文本中的文本。每个打印的文本都在单独的行上。

  2. 每打印第三次文本就打印一个空行。

  3. 编写一个main 方法,其中包含一个或多个writeTexts 调用以及适当的测试数据(不知道这是什么意思),以检查该方法是否适用于所有情况。

    李>

我是一个初学者,觉得这个很难,一直在阅读和观看教程,也搜索并发现了一个类似的问题,但似乎无法掌握这一点。任何帮助表示赞赏。

我在运行代码时遇到的错误是:

cannot find symbol.

到目前为止我得到了什么:

public class Task {

    static void writeTexts(String text, int amount) {
        amount = 0;
        text = "hallo";
        while (amount< 3) {
            System.out.println(text);
            amount++;
        }
    }

    public static void main(String[] args) {
        writeTexts(text);

    }
}

【问题讨论】:

  • 请提供您得到的完整错误信息。
  • 方法writeTexts 需要两个参数,但在main 中只提供一个参数。

标签: java variables parameters while-loop


【解决方案1】:
static void writeTexts(String text, int amount) {
    for(int i = 0; i < amount; i++){
        //Check if the line is the a multiple of 3
        //then print an empty line
        //I use i + 1 because I start at 0 which is a multiple of 3
        //but we are not interested by the that
        if( (i + 1) % 3 == 0 ){
            System.out.println("");
        }
        //Print the text
        System.out.println(text);
}

现在对于calls of writeTexts with appropriate test data,这实际上意味着使用适当的参数调用函数,例如:writeText("Halo 3", 3)。 我强烈建议您阅读更多关于函数的内容,以便更好地了解它们的工作原理。

【讨论】:

    【解决方案2】:
    • 您正在用0 覆盖amount,并且您正在用“hallo”覆盖text,这是不正确的,因为您将打印“hallo”而不是text,并且您忘记了需要多少时间打印。

      amount = 0;
      text = "hallo";
      
    • 您的循环将始终只迭代 3 次。相反,您应该迭代 amount 次。为此,您还需要一个计数器i

      int i = 0;
      while (i < amount) {
      
    • 您不是每第三次打印文本就打印一个空行。你应该添加这个:

      i++;
      if (amount % 3 == 0) { // If amount is divisible by 3
          System.out.println();
      }
      

    【讨论】:

    • 好的,我这样做了:public class Task { static void writeTexts(String text, int amount) { int i = 0; while (amount
    • 在你问为什么它不起作用之前,请仔细检查你的工作。你所要做的就是复制我正确提供的代码,而你没有。
    猜你喜欢
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多