Here is my code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtFirstNum = (EditText) findViewById(R.id.txtFirstNum);
final EditText txtSecondNum = (EditText) findViewById(R.id.txtSecondNum);
final TextView txtResult = (TextView) findViewById(R.id.lblResult);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int num1 = Integer.parseInt(txtFirstNum.getText().toString());
int num2 = Integer.parseInt(txtSecondNum.getText().toString());
int result = num1 + num2;
txtResult.setText(result + "");
}
});
Button btnSub = (Button) findViewById(R.id.btnSub);
btnSub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int num1 = Integer.parseInt(txtFirstNum.getText().toString());
int num2 = Integer.parseInt(txtSecondNum.getText().toString());
int result = num1 - num2;
txtResult.setText(result + "");
}
});
}
}
what I essentially want to do is use a method which I can call instead of repeating the same lines of code kind of like this (which does not work):
int num1;
int num2;
btnAdd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
getNumbers();
int result = num1 + num2;
txtResult.setText(result + "");
}
});
...
private void getNumbers()
{
num1 = Integer.parseInt(txtFirstNum.getText().toString());
num2 = Integer.parseInt(txtSecondNum.getText().toString());
}
Why don't you create two similar to getNumber methods but not void
private int getFirstNumber()
{
return Integer.parseInt(txtFirstNum.getText().toString());
}
private int getSecondNumber()
{
return Integer.parseInt(txtFirstNum.getText().toString());
}
and use them in:
#Override
public void onClick(View v)
{
int result = getFirstNumber() + getSecondNumber();
txtResult.setText(result + "");
}
you have to make num1 et num2 properties of the class
Related
I'm almost new to android and trying to write a calculator code.
It's almost done but I want to try some other options for that
when I repeat clicking on equal button,I want to repeat last calculation entered.for example 3+5=8 then if I click on exe button again it would be 13(3+5+5)
and so on(18,23,...)
Also I have problem with entering more than two numbers.for example when I enter (4+5+6)and then click equal the answer will appear 11 and just calculates last two numbers entered.I want it to show the result of first two numbers then get other numbers.example:for(2+3*4-5/)->the output will be equal to (5->20->15)
Here is my code;If any one can help,I will be grateful! :) thanks
package com.example.sony.calculator;
public class MainActivity extends AppCompatActivity {
Float firstNumber,secondNumber,result;
Float thirdNumber;
TextView display;
Button one,two,three,four,five,six,seven,eight,nine,zero,exe,clear,multiply,divide,sum,minus;
boolean isSum,isMinus,isMultiply,isDivide,isEqual;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.khali);
one = (Button) findViewById(R.id.adade1);
two = (Button) findViewById(R.id.adade2);
three = (Button) findViewById(R.id.adade3);
four = (Button) findViewById(R.id.adade4);
five = (Button) findViewById(R.id.adade5);
six = (Button) findViewById(R.id.adade6);
seven = (Button) findViewById(R.id.adade7);
eight = (Button) findViewById(R.id.adade8);
nine = (Button) findViewById(R.id.adade9);
zero = (Button) findViewById(R.id.adade0);
multiply = (Button) findViewById(R.id.zarb);
divide = (Button) findViewById(R.id.taghsim);
sum = (Button) findViewById(R.id.jam);
minus = (Button) findViewById(R.id.menha);
exe = (Button) findViewById(R.id.mosavi);
clear = (Button) findViewById(R.id.pak);
final Button[] operators = new Button[5];
operators[0] = multiply;
operators[1] = divide;
operators[2] = sum;
operators[3] = minus;
operators[4] = exe;
final Button[] numbers = new Button[10];
numbers[0] = zero;
numbers[1] = one;
numbers[2] = two;
numbers[3] = three;
numbers[4] = four;
numbers[5] = five;
numbers[6] = six;
numbers[7] = seven;
numbers[8] = eight;
numbers[9] = nine;
for (int a = 0; a < 10; a++) {
final int finalA = a;
numbers[a].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText(display.getText().toString() + String.valueOf(finalA));
}
});
}
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText("");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
display.setText("");
return;
}
else{
firstNumber = parseFloat(display.getText().toString());
isSum=true;
display.setText("");
return;
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
display.setText("");
}else {
firstNumber = parseFloat(display.getText().toString());
isMinus = true;
display.setText("");
}
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
Toast Error1=Toast.makeText(MainActivity.this,"Error;Please enter right format",Toast.LENGTH_SHORT);
Error1.show();
}else {
firstNumber = parseFloat(display.getText().toString());
isMultiply = true;
display.setText("");
}
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
Toast Error1 = Toast.makeText(MainActivity.this, "Error;Please enter right format", Toast.LENGTH_SHORT);
Error1.show();
} else {
firstNumber = parseFloat(display.getText().toString());
isDivide = true;
display.setText("");
}
}
});
exe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isEqual=true;
if (display.getText() == "") {
display.setText("");
}
else {
secondNumber = parseFloat(display.getText().toString());
if (isSum == true) {
result = firstNumber + secondNumber ;
display.setText(String.valueOf(result));
isSum=false;
return;
}
if (isMinus == true) {
result = firstNumber - secondNumber;
display.setText(String.valueOf(result));
isMinus = false;
return;
}
if (isDivide == true) {
result = firstNumber / secondNumber;
display.setText(String.valueOf(result));
isDivide = false;
return;
}
if (isMultiply == true) {
result = firstNumber * secondNumber;
display.setText(String.valueOf(result));
isMultiply=false;
return;
}
}
}
});
}
}
How can I make the random number change after user got the right number? I tried while, but it seems that if I use while, the number is always true so it's going to make an infinite loop
final TextView randomnumber = (TextView) findViewById(R.id.randomTextView);
final EditText number = (EditText) findViewById(R.id.editText2);
final EditText number2 = (EditText) findViewById(R.id.editText);
final EditText yourchoose = (EditText) findViewById(R.id.choose);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int d = (int) (Math.random() * (a - b) + b);
int c = Integer.parseInt(yourchoose.getText().toString());
if(d > c) {
randomnumber.setText("Choose Bigger");
} else if (d < c) {
randomnumber.setText("Choose Smaller");
} else {
randomnumber.setText("You're Right, The number is " + d);
}
}
});
Generate a random number outside onClick. Remove the while loop from the onClick.
See the code below,
final TextView randomnumber = (TextView) findViewById(R.id.randomTextView);
final EditText number = (EditText) findViewById(R.id.editText2);
final EditText number2 = (EditText) findViewById(R.id.editText);
final EditText yourchoose = (EditText) findViewById(R.id.choose);
Random rand = new Random();
final int randomNumber = rand.nextInt();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int c = Integer.parseInt(yourchoose.getText().toString());
int random = (int) (randomNumber * (a - b) + b);
if (random > c) {
randomnumber.setText("Choose Bigger");
} else if (random < c) {
randomnumber.setText("Choose Smaller");
} else {
randomnumber.setText("Your're Right, Number is " + random);
}
}
});
EDIT
On having a look again, the random number generated should be between the following range
b < randomNumber < (a - b)
So I used a TextWatcher to listen to the chnage on the number and number2 EditText.
// Before onCreate
int a = 0, b = 0, c, random = 0;
//inside onCreate
final TextView randomnumber = (TextView) findViewById(R.id.randomTextView);
final EditText number = (EditText) findViewById(R.id.editText2);
final EditText number2 = (EditText) findViewById(R.id.editText);
final EditText yourchoose = (EditText) findViewById(R.id.choose);
final Random rand = new Random();
number.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
a = Integer.parseInt(number.getText().toString());
random = rand.nextInt(a - b) + b;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int count, int after){}
});
number2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
b = Integer.parseInt(number2.getText().toString());
random = rand.nextInt(a - b) + b;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int count, int after){}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c = Integer.parseInt(yourchoose.getText().toString());
if (random > c) {
randomnumber.setText("Choose Bigger");
} else if (random < c) {
randomnumber.setText("Choose Smaller");
} else {
randomnumber.setText("Your're Right, Number is " + random);
}
}
});
Because the value of c and random is not changing in a while loop, so it goes on.
For example: if value of random is 5 and c is 3. Once it enters the loop, the values remains the same and while(random!=c) is always true, so it's not going to stop.
So I'm new to java and I'm trying to make quiz app as exercise. I kinda made one but it doesn't work:
public class QuizActivity extends AppCompatActivity {
TextView QuestionText;
Button button1;
Button button2;
Button button3;
Button button4;
ArrayList<Question> listOfQuestions;
int currentQuestion = 0;
Context context = this;
int NumberOfQuestions;
GameCreator game;
String totalCorrect = "";
String totalWrong = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuestionText = (TextView) findViewById(R.id.textJautajums);
button1 = (Button) findViewById(R.id.buttonOpcija1);
button2 = (Button) findViewById(R.id.buttonOpcija2);
button3 = (Button) findViewById(R.id.buttonOpcija3);
button4 = (Button) findViewById(R.id.buttonOpcija4);
NumberOfQuestions = Integer.parseInt(context.getString(R.string.JautajumuSkaits).toString());
game = new GameCreator(NumberOfQuestions);
listOfQuestions = game.makeQuestions();
Resources r = getResources();
int px1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 165, r.getDisplayMetrics());
button1.setWidth(px1);
button2.setWidth(px1);
button3.setWidth(px1);
button4.setWidth(px1);
Resources e = getResources();
int px2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 125, r.getDisplayMetrics());
button1.setHeight(px2);
button2.setHeight(px2);
button3.setHeight(px2);
button4.setHeight(px2);
if (currentQuestion == 0){
setQuestion(listOfQuestions.get(0));
}
button1.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button1.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button2.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button2.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button3.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button3.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button4.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button4.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
}
public void gajiens(String answer, Question thisQuestion){
if (currentQuestion < 14){
if (answer.equals(thisQuestion.getAnswer())){
totalCorrect += "Question: " + thisQuestion.getQuestion() + "\nYour Answer: " + answer + "\n";
} else {
totalWrong += "Question: " + thisQuestion.getQuestion()) + "\nYour Answer: " + answer + "\n";
}
currentQuestion++;
setQuestion(listOfQuestions.get(currentQuestion));
} else {
Intent intent = new Intent(this, EndActivity.class);
intent.putExtra("correct", totalCorrect);
intent.putExtra("wrong", totalWrong);
startActivity(intent);
}
}
public void setQuestion(Question kursh){
QuestionText.setText(kursh.getJautajums());
button1.setText(kursh.getOption1());
button2.setText(kursh.getOption2());
button3.setText(kursh.getOption3());
button4.setText(kursh.getOption4());
}
object Question is:
public Question(String Question, String Option1, String Option2, String Option3,String Option4, String correctAnswer){
Question = Question;
Option1 = Option1;
Option2 = Option2;
Option3 = Option3;
Option4 = Option4;
correctAnswer = correctAnswer;
}
Basically the problem is that App doesn't count the right answers. For some reason it most of the time uses the original text of TextView as ''correctAnswer''. Anyone has any idea what to do? I suspect since this isn't working properly this isn't particularly best approach so maybe someone can suggest a better one?
to compare the value of a TextView with a String you can do this as below
TextView tvAnswer = (TextView) findViewById(R.id.tvAnswer);
String correctAnswer = "Correct Answer";
if(correctAnswer.equals(tvAnswer.getText.toString()) )
{
//do something
}
else{
//do something
}
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
I'm very new in Android programming, and i'm trying to sum all char elements from datepicker, but with no success.
here is code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
char[] c = sdate.toCharArray();
for(int i=0; i<c.length;i++)
{
num+=Integer.valueOf(c[i]);
}
tv.setText(String.valueOf(num));
}
});
}
and output is: 355.
Real sum must to be 20, i want to sum like this 17/06/2013,
so example 1+7+0+6+2+0+1+3 = 20
use Character.getNumericValue
for(int i=0; i<c.length;i++) {
num+=Character.getNumericValue(c[i]);
}
This will work
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tv = (TextView)findViewById(R.id.textView1);
DatePicker dp = (DatePicker)findViewById(R.id.datePicker1);
final int day = dp.getDayOfMonth();
final int month = dp.getMonth();
final int year = dp.getYear();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int num = 0;
String sdate = String.valueOf(month) + String.valueOf(day) + String.valueOf(year);
int[] ee=new int[sdate.length()];
String[] dd=new String[sdate.length()];
for(int i=0;i<sdate.length();i++){
dd[i]=sdate.substring(i,i+1);
ee[i]=Integer.parseInt(dd[i]);
num+=ee[i];
}
tv.setText(String.valueOf(num));
}
});
}
Change from Integer.valueOf() to Character.valueOf() Integer.valueOf(int) takes integer, your char is being cast to int and gives ASCII value.