Question

I need to use euclidian algorithm in my android program. Here is my main activity:

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView answer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    answer = (TextView) findViewById(R.id.textView1);

     Button proceed = (Button) findViewById(R.id.button1);
     proceed.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                int ans = Euclid.gcd(6, 9);
                answer.setText(ans);
            }
        });
       }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


}

The thing that I want my program to do, is give me Greatest Common Division(GCD) when I click the button. And I'm trying to do it with this part of code:

public void onClick(View v) {
int ans = Euclid.gcd(6, 9);
answer.setText(ans);
}

And here is my Euclid class:

public class Euclid {

// recursive implementation
public static int gcd(int p, int q) {
    if (q == 0) return p;
    else return gcd(q, p % q);
}

// non-recursive implementation
public static int gcd2(int p, int q) {
    while (q != 0) {
        int temp = q;
        q = p % q;
        p = temp;
    }
    return p;
}

public static void main(String[] args) {
    int p = Integer.parseInt(args[0]);
    int q = Integer.parseInt(args[1]);
    int d  = gcd(p, q);
    int d2 = gcd2(p, q);
    System.out.println("gcd(" + p + ", " + q + ") = " + d);
    System.out.println("gcd(" + p + ", " + q + ") = " + d2);
}
}

The thing is, that when I click the button my app crashes. So where is the problem and how can I fix it. I know it is in void onClick part. Please help.

Was it helpful?

Solution

TextView.setText(int)'s integer argument is a resource id, not a literal integer to display. Instead use something like

answer.setText(Integer.toString(ans));

To display the integer in the TextView.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top