how can i match an iteration variable to the input variable in edit text, i wanted to create the armstrong number
it goes like this
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
tv2.setText(sum);
for (int i = 0; i < 5; i++) {
if (i==1){
(1 == 153)
}
}
}
});
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button check;
private TextView result;
private EditText input_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check =(Button) findViewById(R.id.button_check);
check.setOnClickListener(this);
result =(TextView)findViewById(R.id.result);
input_number =(EditText)findViewById(R.id.input_number);
}
#Override
public void onClick(View v) {
int num = Integer.parseInt(input_number.getText().toString());
int n = num;
int check =0,remainder;
while(num>0){
remainder = num % 10;
check = (int) (check + Math.pow(remainder,3));
num = num/10;
}
if(check == n)
result.setText(n+"is an Armstrong Number");
else
result.setText(n+"is not an Armstrong Number");
}
}
To confirm if user input is an armstrong number, you don't need to iterate. You simply need to compute sum of the cube of individual digits and confirm if it arithmetically equals the value of the figure of the digits when combine.
Your code will thus be refactored like below to solve the problem
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer one = Integer.parseInt(edt1.getText().toString());
Integer two = Integer.parseInt(edt2.getText().toString());
Integer three = Integer.parseInt(edt3.getText().toString());
// convert input text to three fields to one String
String joinedText = "" + one + two + three;
Integer num1 = (one * one * one);
Integer num2 = (two * two * two);
Integer num3 = (three * three * three);
Integer sum = (num1 + num2 + num3);
// you must setText as String
tv2.setText(Integer.toString(sum));
if(sum == Integer.parseInt(joinedText)){
// This is an armstrong number
}else {
// This is not an armstrong number
}
}
});
Related
I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?
I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});
I have two Button + and - when i click on the + button the value increases in the textview and vice versa. but i want to multiply the textview number to the price and change the price accordingly.
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCategory pojoCategory = (PojoCategory) v.getTag();
int mValue = pojoCategory.getmQuantity();
mValue++;
viewHolder.tv_Number.setText("" + mValue);
pojoCategory.setmQuantity(mValue);
String value1 = viewHolder.tv_Number.getText().toString();
String value2 = pojoCategory.getDish_rate();
Log.e("value1", value1);
Log.e("value2", value2);
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
int z = x * y;
Log.e("z", "" + z);
viewHolder.Dish_rate.setText(String.valueOf(z));
notifyDataSetChanged();
}
});
This question already has an answer here:
android number format exception
(1 answer)
Closed 7 years ago.
This is my calculator app, I know that NumberFormat are caused when we try convert string to numerical type.I have also surrounded them by TRY/CATCH but i cant seem to get them as INT values. Here in my app, I'm getting the strings in the textview and trying to perform operations on them.
Can anyone suggest an alternative approach for the problem?
Here's the code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
private static String GAT = "Tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ArrayList<String> arrayList = new ArrayList<String>();
String stringOne = " ";
String stringTwo = " ";
public void onClick1(View view) {
//Getting Input from TextView
TextView inputText = (TextView) findViewById(R.id.inputTextView);
Button button = (Button) view;
//Store as String from button press
stringOne = (String) button.getText().toString();
Log.d(TAG, stringOne);
//For entering multiple values
if (!stringOne.contains("+") && !stringOne.contains("-") && !stringOne.contains("/") && !stringOne.contains("*")) {
//Concat if it has multiple digits to original string
stringTwo = stringTwo + stringOne;
Log.d(TAG, stringTwo);
//Remove the last string and place as StringTwo
if (arrayList.size() > 0) {
//Get last position in the array
arrayList.remove((arrayList.size() - 1));
}
arrayList.add(stringTwo);
} else {
//For operators add two times because we removed the previous index
arrayList.add(stringOne);
arrayList.add(stringOne);
//Clear
stringTwo = " ";
Toast.makeText(this, stringOne, Toast.LENGTH_LONG).show();
Log.d(TAG, stringOne);
// Log.d("Veer",stringTwo);
}
//Add to TextView
inputText.setText(inputText.getText().toString()+stringOne);
//inputText.setText(arrayList.toString());
}
public void calculate(View view) {
TextView outputText = (TextView) findViewById(R.id.outputTextView);
int result = 0;
int list = arrayList.size();
while (list != 1) {
if (list > 3) {
//Considering the equation to be like 4+5*5-2/4, Get the third operator, if * and /, then multiply
if (arrayList.get(3).contains("*") || arrayList.get(3).contains("/")) {
if (arrayList.get(3).contains("*")) {
result = Integer.parseInt(arrayList.get(2)) * Integer.parseInt(arrayList.get(4));
} else if (arrayList.get(3).contains("/")) {
result = Integer.parseInt(arrayList.get(2)) / Integer.parseInt(arrayList.get(4));
}
arrayList.remove(2);
arrayList.remove(2);
arrayList.remove(2);
arrayList.add(2, Integer.toString(result));
list = arrayList.size();
} else {
//Vice versa, here for + and - ,replace 1st and 2nd digit
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
else
{
//If size is 3
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
outputText.setText(Integer.toString(result));
}
public void clearView(View view) {
TextView input = (TextView)findViewById(R.id.inputTextView);
TextView output = (TextView)findViewById(R.id.outputTextView);
stringOne = "";
stringTwo = "";
input.setText("");
output.setText("");
arrayList.clear();
}
}
You need to catch exception whenever you convert string to numerical type. If it throw an exception then you return. And if no exception, you continue to perform operations on them.
String text = "";
int num;
try {
num = Integer.parseInt(text);
// text is a number");
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Can not parse string to int: " + text,Toast.LENGTH_LONG).show();
// text is not a number";
// Show Log or make a Toast here to easy see when String is not Int format. After that find the reason why text is not int format
}
Hope this help
float num1 = 0;
float num2 = 0;
float result = 0;
num1 = Float.parseFloat(etNum1.getText().toString());
num2 = Float.parseFloat(etNum2.getText().toString());
result = num1 * num2 ;
Log.e("Result",""+result);
Hope it helps.
I want to create an application in which the user has 90 seconds in order to complete a certain number of sums.
I am unsure how to stop the activity and move to another after the timeframe is up?
Activity code:
/**
* Class holding the activity that has the 10 random sums for the user to answer
* #author Ross
*
*/
public class RandomTest extends Activity implements View.OnClickListener {
// declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String[] question = new String[10];
int correctAnswer[] = new int[10];
int[] results = new int[10];
int score = 0;
int questionNumber = 1;
MediaPlayer correctNoise;
MediaPlayer incorrectNoise;
ImageView imageRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
// set up random
setUpRandom();
// Set text view equal to question in array
text.setText(question[questionNumber - 1]);
// set on click listener for the submit button
submit.setOnClickListener(this);
// updateQuestion
updateQuestion();
}
/**
* Method that initialises variables
*/
public void initialiseVars() {
correctNoise = MediaPlayer.create(RandomTest.this, R.raw.correctnoise);
incorrectNoise = MediaPlayer.create(RandomTest.this, R.raw.incorrectnoise);
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
imageRandom= (ImageView) findViewById(R.id.imageViewRandomTest);
}
/**
* Method that creates the random sum for user to answer
*/
public void setUpRandom() {
// setting up new random
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
// Creating random question String
question[questionNumber - 1] = random1 + " x " + random2 + " = ";
// Creating correct answer to question
correctAnswer[questionNumber - 1] = random1 * random2;
}
/**
* Method that updates question after each click
*/
public void updateQuestion() {
// updating question after each click
setUpRandom();
text.setText(question[questionNumber - 1]);
answer.setText("");
}
public void onClick(View v) {
// sets text view equal to what is entered in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //
// setting the user answer equal to the correct part of results array
results[questionNumber - 1] = a;
// If user answer is equal to correct answer then increase score
if (a == correctAnswer[questionNumber - 1]) {
score++;
correctNoise.start();
imageRandom.setImageResource(R.drawable.thumbsup);
}else{
incorrectNoise.start();
imageRandom.setImageResource(R.drawable.thumbsdown);
}
// if question number is under 10
if (questionNumber < 10) {
// updates question number
questionNumber++;
// called after an answer is given
updateQuestion();
} else {
// Passing values to the results activity
Intent intent = new Intent(this, RandomTestResults.class);
intent.putExtra("results", results);
intent.putExtra("Questions", question);
intent.putExtra("CorrectAnswer", correctAnswer);
intent.putExtra("score", score);
// Start Activity
this.startActivity(intent);
}
}
}
Use the AlarmManager and when it calls use finish();