【问题标题】:android variables not incrementing inside loopandroid变量不会在循环内递增
【发布时间】:2015-11-28 06:46:47
【问题描述】:

我正在尝试编写一个简单的 android 程序,它将按以下格式将 99 瓶啤酒的歌词打印在墙上。

第 1 行:墙上有 99 瓶啤酒……

第 2 行:墙上有 98 瓶啤酒……

等等。

我正在尝试创建一个循环来打印第一行歌词,然后递增/递减变量“lineNumber”、“numOfBottles”和“lessNumOfBottles”。

我尝试了几种不同的方法和运算符,但我的变量在编译时从未改变,而且每行歌词都得到相同的重复数字。

我做错了什么? (cmets 中的底部循环是我尝试过的第一个循环,我只是将其作为自己的参考)

protected void onResume(){
    super.onResume();


    int lineNumber = 1;
    int numOfBottles = 99;
    int lessNumOfBottles = 98;
    String line = "Line " + lineNumber + ":\n";
    String lyrics= "Lyrics to 99 bottles of beer \n\n";
    String song =line +  numOfBottles + " bottles of beer on the wall," + numOfBottles + " bottles of beer, take one down, pass it around," + lessNumOfBottles + " bottles of beer on the wall.\n\n";


    TextView textview = (TextView) findViewById(R.id.myTextView);

    textview.setText(lyrics);

    for(int i = 99;i >= 1;i--) {
        if (numOfBottles >= 1) {
            textview.append(song);
            --numOfBottles;
            --lessNumOfBottles;
            ++lineNumber;
        }
    }

    /*for (int i=0;i<99;){
        lineNumber++;
        numOfBottles= --numOfBottles;
        lessNumOfBottles= --lessNumOfBottles;
        textview.setText(song);
        textview.append(song);
        i++;
    }*/
}

【问题讨论】:

  • 是的,它们是......但它没有显示......因为你阻塞了主线程并且没有时间在增量之间重绘屏幕......
  • @Selvin,即使他阻塞了主线程,在循环执行后,他增加变量的事实并不重要,因为它不会改变他的 Strings 的结果.

标签: java android loops operators increment


【解决方案1】:

您只将字符串的值分配给lineNumbernumOfBottleslessNumOfBottles 的第一个值。 linesong 变量永远不会更新。

试试这个:

protected void onResume(){
    super.onResume();


    int numLines = 100;
    int numOfBottles = 99;
    String line;
    String lyrics= "Lyrics to 99 bottles of beer \n\n";

    TextView textview = (TextView) findViewById(R.id.myTextView);

    textview.setText(lyrics);

    for(int i = numOfBottles;i >= 1;i--) {
        if (numOfBottles >= 1) {
            line = "Line " + numLines-i + ":\n";
            textview.append(line + i + " bottles of beer on the wall," + 
                             i + " bottles of beer, take one down, pass it around," + 
                             i-1 + " bottles of beer on the wall.\n\n");
        }
    }
}

【讨论】:

  • 我想我假设由于通过向它们添加值来声明字符串变量,因此每次调用字符串时都会重新声明它。我知道我错在哪里了,谢谢!
  • 是的,我知道你在哪里感到困惑。我添加了一个可能的解决方案来帮助您。
猜你喜欢
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多