so I believe I am overthinking this but I want to double check.
I am getting my TextView from my EditText widget.
addMileage.setOnClickListener(new OnClickListener() {
#Override
public void OnClick(View v) {
if (isErase) {
nextMileage.setText(mileageInput.getText().toString());
} else {
nextMileage.setText("");
}
isErase = !isErase;
}
How can I take what the user enters in the EditText then automatically take the number entered and + 3500. Then display in TextView?
int result=Integer.parseInt(mileageInput.getText().toString())+3500;
nextMileage.setText(result+"");
You can do like this
onClick
String s = your_editText.getText().toString();
if (!s.trim().equals("")
{
int i = Integer.parseInt(s);
int sum = i + 3500;
your_textView.setText(" " + sum);
}
else
your_textView.setText("Please enter the number");
Assuming the code you have works (you didn't say it doesn't work), you can edit the if body as
if (isErase) {
String mileageStr = (Integer.parseInt(mileageInput.getText().toString()) + 3500) + "";
nextMileage.setText(mileageStr);
}
Integer.parseInt() allows you to convert a string to an integer quickly.
Related
I'm trying to create a simple calculator that is automatic - no more equal sign. Here's how it should go:
1. User inputs the first number.
2. User chooses an operation "add", "subtract" etc.
3. User inputs the second number. In this stage, the program should now automatically compute the answer. For example:
user inputs "2" as the first number;
user chooses "add";
user inputs "3" (second number this time)
it should then display "5" in the result box.
if the user continues to input "2", this means the second number is now "32" instead of "3", and the result will be "34"
Here's my code:
public String int_firstnumber = "";
public String int_secondnumber = "";
public int int_result = 0;
public int int_numberone = 0;
public int int_numbertwo = 0;
public String str_operation = "";
public String str_inputdisplay = "";
public String str_indicator = "none";
public String str_focus = "first";
// BUTTON 1
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checks the indicator
if(str_focus=="first") {
int_firstnumber = int_firstnumber +"1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
} else {
if(str_indicator=="add"){
int_secondnumber = int_secondnumber + "1";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
int_numberone = Integer.parseInt(int_firstnumber);
int_numbertwo = Integer.parseInt(int_secondnumber);
int_result = int_numberone + int_numbertwo;
lblresult.setText(int_result);
}
}
}
});
//END OF BUTTON 1
//BUTTON ADD
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
str_indicator = "add";
str_operation = " + ";
str_focus = "second";
lblinput.setText(int_firstnumber + str_operation + int_secondnumber);
}
});
This somewhat works but not completely. If I Input "1", it'll display 1 on the str_inputdisplay, I then click the + symbol or the btnadd, it then displays 1+ in the str_inputdisplay. This means that we are on the second number right? However when I input 1 again, the app just force closes.
Any ideas why this is happening? Forgive my ways of code, I just started learning Java btw. Thanks!
why are you naming your variable 'int_firstnumber' when it's a string public String int_firstnumber when all your other variables are named according to the variable type like int int_result and str_operation
your code looks a bit more complicated then it needs to be. as someone mentioned you can't add two numbers when your operator is a string i.e. string operator = "+"; it won't get treated like an operand, it will get treated for the type it is which is a string.
why not if they select "first" call a method setFirstNumber that way you can validate input and set the first number.. something like this:
public void setFirstNumber(int firstNumber){
int_numberone = firstNumber;
}
and then when "add" gets selected call a second method setSecondNumber along with an addition method
public void setSecondNumber(int secondNumber){
int_numbertwo = secondNumber;'
}
and
public int addNumbers(int firstNumber, int secondNumber){
return firstNumber + secondNumber;
}
your result will be int_result = addNumbers(int_numberOne, int_numberTwo)
this way your code is much cleaner, each function is executing one task, and if you want to add additional operations later it's easy to add a function subtract, multiply, etc
public int subtractNumbers(int firstNumber, int secondNumber){
return firstNumber - secondNumber;
}
public int multiplyNumbers(int firstNumber, int secondNumber){
return firstNumber * secondNumber;
}
hope that helps!
You should add TextWatcher to the input fields. You will get the values in callbaks there which you can use to update the view showing answer.
Two issues:
When adding two strings, addition will not happen. Change it to int, long etc when you want to do operation like:
int_firstnumber = int_firstnumber +"1";
Hopefully you are properly setting the variables str_focus and str_indicator because that is not available in the code snippet you have given.
if("first".equals(str_focus)) {
......
int_firstnumber = int_firstnumber +1;
} else {
if("add".equals(str_indicator)){
......
int_secondnumber = int_secondnumber + 1;
I use the debugger to find that the value of townHallLvl stays 1 at the end
Please help
int townHallLvl = 1;
public void addTownHall(View v){
if (townHallLvl == 11) {
Toast.makeText(this, "You can't have more than Town Hall lvl 11!!!", Toast.LENGTH_SHORT).show();
return;
}
add(townHallLvl);
TextView townHallText = (TextView) findViewById(R.id.town_hall_lvl);
townHallText.setText(String.valueOf(townHallLvl));
}
public int add(int lvl){
int ans = lvl + 1;
return ans;
}
townHallLvl = add(townHallLvl);
You probably missed to assign back the value to townHallLvl.
So here's my problem its been bugging me for a while but when I try to get the text from a textview (custom number picker) and add it as an array value, the array won't let me input the textview value (sonyR).
Custom number picker widget :
#Override
public void onClick(View v) {
String getString = String.valueOf(tvSony.getText());
int current1 = Integer.parseInt(getString);
if (v == btnUp1) {
if (current1 < nEnd) {
current1++;
tvSony.setText(String.valueOf(current1));
}
}
if (v == btnDown1) {
if (current1 > nStart) {
current1--;
tvSony.setText(String.valueOf(current1));
}
}
sonyR = current1;
Log.i("sonyR ouput =", String.valueOf(sonyR));
Array, if value has been entered before, find the value and display it. if not make a new array value
private void sun32() {
ArrayList<Integer> sun32A = new ArrayList<Integer>();
if (sun32A.contains(sonyR)) {
sun32A.get(Integer.valueOf(sonyR));
tvSony.setText(sonyR);
} else {
tvSony.getText(Integer.valueOf(sonyR));<-----here is the error
sun32A.add(sonyR);
}
return;
}
EDIT : Just to confirm here is an image of the UI layout
One problem in your posted code is that getText() shouldn't take any arguments.
Also, TextView.getText() returns a CharSequence, not a String. You should convert it by doing toString() before calling Integer.valueOf(). Try this code and see if it works:
ArrayList<Integer> sun32A = new ArrayList<Integer>(); <---- Variable moved to outside of method.
private void sun32() {
if (sun32A.contains(sonyR)) {
// removed irrelevant code line
tvSony.setText(String.valueOf(sonyR)); <----- Convert the int to String before setting text.
} else {
int myInt = Integer.valueOf(tvSony.getText().toString()); <----- fixed code
sun32A.add(myInt);
}
return;
}
I wanted to make an app that would get the test score from the text field (id etxt1) and on a click of a button it would show the grade in the other text field (id etxt2).
marks 100-91 grade A.
marks 90-81 grade B.
marks 80-71 grade C.
and so on.
and how to use the ">=" thing.
Here's my code:
Button bt1;
EditText etxt1;
EditText etxt2;
char grade = 0;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activitywhatsyourgrade);
bt1 = (Button) findViewById(R.id.button1);
etxt1 = (EditText) findViewById(R.id.testscore);
final int score = etxt1.getTextAlignment();
etxt2 = (EditText) findViewById(R.id.editText2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (score == 90){
etxt2.setText("A1");
}
else if (score ==80){
etxt2.setText("A2");
}
}
});
}
#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_activitywhatsyourgrade, menu);
return true;
}
There are a couple things wrong.
final int score = etxt1.getTextAlignment(); is incorrect because:
You define it outside of the button listener, and as final, so it never changes depending on input.
getTextAlignment() is not the function you want to call.
Here's how to fix it:
Get rid of that line of code all together. We'll replace that in the button listener.
We'll use getText() method to get the text from the EditText. It won't be returned as a String, but instead an Editable, so we'll use the toString() method on that to use it as a String.
Once we have the String representation of the score, we'll parse that to an integer to check which range of grade it's between.
This code is just for your button listener. Just replace it with this. It's self explanatory, so I won't give any more explanation for it.
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strScore = etxt1.getText().toString();
int score = Integer.parseInt(strScore);
if (score >= 91) {
etxt2.setText("A");
}
else if (score >= 81) {
etxt2.setText("B");
}
else if (score >= 81) {
etxt2.setText("B");
}
else if (score >= 71) {
etxt2.setText("C");
}
else if (score >= 61) {
etxt2.setText("D");
}
else {
etxt2.setText("F");
}
}
});
This next section is just extra, you don't have to read this part if you're not completely understanding the code so far:
You may run into a problem where if the field is left blank when the button is pressed, your app will crash. This is because you're trying to parse an empty string (which is "") to a numerical value, which obviously cannot be done. The same thing will happen if the field is just a negative sign or decimal point.
To fix that, you can just wrap the part of your code that is parsing the String to an integer in a try-catch block. This will catch an exception that will be thrown for the problem stated above. Like this:
Replace this line:
int score = Integer.parseInt(strScore);
With this:
int score = 0;
try {
score = Integer.parseInt(strScore);
} catch (NumberFormatException nfe) {
// This means NFE was thrown, so the field text cannot be parsed
// to a numerical value. Just leave score = 0 as it was initialized
}
Or you can use an if-statement to test if the input is valid (this solution is worse because it only catches three cases when there could possibly be more, depending on the keyboard restrictions):
int score = 0;
// if the input is not blank, a negative sign or a decimal point
if (!(strScore.equals("") || strScore.equals("-") || strScore.equals(".")) {
score = Integer.parseInt(strScore);
}
String a = etxt1.getText().toString();
etxt2.setText(a);
I would like to add an amendment to Mike Yaworski's answer
While this code is correct that he gave...
#Override
public void onClick(View v) {
String strScore = etxt1.getText().toString();
int score = Integer.parseInt(strScore);
...
... there is a fundamental flaw in that getText() can and will return null if the field is left blank. That is because it is not returning a String - it is returning an Editable; hence why you have to call toString() on it.
Here is my correction to it. Note, I had to get the text from 2 items in the GUI, so I separated the logic into a private method that returned the given String
// Returns a String from and Editable. Deals with the null value
private String extractStringNumber(Editable text) {
if (text == null) return "0"; // Change this to fit you needs
return text.toString();
}
#Override
public void onClick(View v) {
String strScore = extractStringNumber(etxt1.getText());
int score = Integer.parseInt(strScore); // This is now guaranteed not to fail as long as strScore can be represented as a number.
I used the following way to change the string into double but unfortunately this closes the app. The EditText inputtype is "NumberDecimal"
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
//App forceclose here. Not sure why.
final Double a = Double.parseDouble(numA.getText().toString());
final Double b = Double.parseDouble(numB.getText().toString());
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
}
});
Try this;
String s = b.getText().toString();
final double a = Double.valueOf(s.trim()).doubleValue();
Perform this check:
if (!numA.getText().toString().equals("")) {
final Double a = Double.parseDouble(numA.getText().toString());
}
if (!numB.getText().toString().equals("")) {
final Double b = Double.parseDouble(numB.getText().toString());
}
An empty string argument to Double.parseDouble() produces a NumberFormatException.
As a suggestion, if you are working on making a calculator(or converter), you should add more checks for invalid input. For example, you should add a check for when the user inputs just the decimal point(.) or input of form (3.).
You may wish to use a try catch because other unparseable data will throw an exception and it may not be the best to rely on the UI to force valid numbers only.
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
Double a;
Double b;
try {
a = Double.parseDouble(numA.getText().toString());
b = Double.parseDouble(numB.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
a = 0.0;
b = 0.0;
}
final double aFin = a;
final double bFin = b;
calculate.setOnClickListener(new View.OnClickListener() {
//Also, you used your class as an onClickListener you would have to make your doubles final.
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
//Division by zero will produce a NaN you should probably check user input data sanity
}
});