【问题标题】:Display each for loop iteration output in android studio在android studio中显示每个for循环迭代输出
【发布时间】:2017-02-02 13:10:22
【问题描述】:

我正在尝试演示由按钮单击触发的插入排序。在输出中显示排序的所有步骤。

输入整数个位数 0-9。

谁能帮我即兴创作我的代码! 非常感谢您的帮助。

O/p 显示大括号和逗号,因为它是一个数组。 我可以在没有大括号和昏迷的情况下获得 o/p 吗? 而不是 o/p [3,5,7,9] 它应该是 - 3 5 7 9

    public void btnClickMe(View v) {
    Button button = (Button) findViewById(R.id.button);
    EditText et = (EditText) findViewById(R.id.editText);
    TextView tv = (TextView) findViewById(R.id.textView2);
    insertionSort();
}
public void insertionSort(){
    EditText et = (EditText) findViewById(R.id.editText);
    String text = et.getText().toString();
    String txt1 = text.replaceAll(","," ");
    String txt= txt1.replaceAll(" ","");
    int[] array = new int[txt.length()];
    for (int i = 0; i < txt.length(); i++){
        array[i] = Character.getNumericValue(txt.charAt(i));
    }
    TextView tv = (TextView) findViewById(R.id.textView2);
    tv.setText("Output:");
    for (int j = 1; j < array.length; j++){
        int key = array[j];
        int i = j - 1;
        while ((i > -1) && (array[i] > key)){
            array[i + 1] = array[i];
            i--;
        }
    }
    array[i + 1] = key;
    tv.append(Arrays.toString(array).replaceAll(",","")+"\n");
}

我可能要求太多,但我正在努力学习 android,你的帮助会教给我很多新东西。提前致谢。

【问题讨论】:

    标签: java android android-studio append settext


    【解决方案1】:

    首先,您的插入算法存在缺陷。 其次,您需要在每次追加之前重置TextView的文本。

    int[] array = {6, 4, 3, 2};
    // TextView tv = (TextView) findViewById(R.id.textView2);
    // Resets the text to be blank.
    // tv.setText("");
    
    for (int i = 1; i < array.length; ++i) {
        int j = i;
        while (j > 0 && array[j - 1] > array[j]) {
            int temp = array[j];
            array[j] = array[j - 1];
            array[j - 1] = temp;
            --j;
        }
        System.out.println(Arrays.toString(array));
        // i.e. [4, 6, 3, 2]
        // tv.append(Arrays.toString(array) + "\n");
    }
    

    【讨论】:

    • 我实际上不想替换。我想显示所有迭代,例如: I/p: 6432 O/p 应该是: 4 6 3 2 3 4 6 2 2 3 4 6 使用 settext 它只显示最后一次迭代,即; 2 3 4 6 我希望你得到了这个问题。
    • 那么,你的意思是——“新的o/p被追加而不是清除旧的o/p并显示新的数组。”
    • 我的意思是:如果我的 i/p 是 421,它会显示 o/p: 2 4 1 1 2 4。然后当我插入新值 (6 4 1) 并单击排序按钮时的文本字段仅显示 4 6 1 1 4 6 而是显示 2 4 1 1 2 4(这是以前的 o/p)附加新的 o/p 4 6 1 1 4 6 对不起,这些复杂的问题。
    • 如果它 --- "而不是文本字段只显示 4 6 1 1 4 6 而是显示 2 4 1 1 2 4(这是以前的 o/p)附加新的 o/p 4 6 1 1 4 6"............然后,您需要使用setText清除“previous o/p”
    • 更新答案。
    猜你喜欢
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 2015-02-10
    • 2021-04-13
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多