How do simple calculating with multiplication only - java

i have problem with my simple calculate with only multiplication from the edittext where the user input the numbers. When user click result button, numbers that user input from edittext do multiplication and show result in textview.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
output1.setText(input.getText()*"2");
output2.setText(input.getText()*"3");
output3.setText(input.getText()*"4");
}
}
(input.getText()*"") showing red underline. It said 'Operator * cannot be applied to android.text.editable, java.lang.String' .
Anyone can fill my code? I m beginners :)

String can not be calculated, you need to convert into numbers in the operation, you can try:
Integer.valueOf ("")

make sure the user inputs a number, use
android:inputType="number"
in the EditText attributes.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// storing the EditText value in a variable.
// do it in the onClick method only.
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(inputVal * 2);
output2.setText(inputVal * 3);
output3.setText(inputVal * 4);
}
}

input => EditText
When you use input.getText() you get object of Editable class.
If you want to get its value, you have to convert Editable to String, using input.getText().toString().
Now you want to multiply the value, So you have to convert String to Integer(or relevant dataType), by Integer.parseInt(input.getText().toString()) and then multiply with your value.
Now you want to assign this updated value to TextView, use String.valueOf().
So finally your code should be:
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(String.valueOf(inputVal * 2));
output2.setText(String.valueOf(inputVal * 3));
output3.setText(String.valueOf(inputVal * 4));

use this
output1.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("2"));
output2.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("3"));
output3.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("4"));

You are trying to multiply strings. You should transform the string into numbers before multipling them.
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
int inputInt = Integer.parseInt(input.getText());
int inputInt_times2 = 2*inputInt;
int inputInt_times3 = 3*inputInt;
int inputInt_times4 = 4*inputInt;
output1.setText(inputInt_times2+"");
output2.setText(inputInt_times3+"");
output3.setText(inputInt_times4+"");
}catch(Exception e){
//handle the exception here
}
}
}
the (+"") that I added in the setText was to transform the int to String again.

Related

Android Java Decimal Format - Zero is hidden after decimal point

In my app, i want to be able to format numbers to string (with commas) in a TextView e.g 123456.000 to 123,456.000. But the problem is when i type zero (0) as the last number after the decimal point, it shows nothing until i type another number. For example, if i type 123456.000, i get 123,456. The zeros doesn't show until i type another number like "1" then i get 123,456.0001. Please how do i make zeros show as last number after decimal point? Below are some sample codes.
I apologise for the clumsiness of the code. I manually typed it with my phone.
TextView txtView;
boolean NumberClicked = false;
String number = "";
// format pattern
DecimalFormat formatter = new DecimalFormat("#,###.#########");
// input dot (decimal point)
dot.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
if (!txtView.getText.toString.contains(".") {
input(".");}}});
// input zero (0)
zero.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
input("0");
}});
// input one (1)
one.setOnClickListener (new
View.OnClickLstener() {
public void onClick(View view) {
input("1");}});
// input method
public void input (String view) {
if (!numberClicked) {
number = view;
numberClicked = true;
} else {
number = number + view;
}
// print the entered numbers to
//the TextView after formatting
if (!number.endsWith(".")) { txtView.setText(formatter.format(Double.parseDouble(number)));}}
enter code here
You may try this code snippet:
DecimalFormat df = new DecimalFormat("#,##0.0#");
df.setMinimumFractionDigits(3);
String value = df.format(123456.000);
Output: 123,456.000
For more info pls click here.
Try with:
String.format("%,.03f", 123456.000)

How Delete Last number of a float in android (java)

I am building a calculator app and everything is working properly but I don't know the code for backspace.
public class MainActivity extends AppCompatActivity {
// UI Elements
private TextView num_input;
private TextView num_input;
private ImageButton num_backspace;
private float input, input2 ;
boolean Addition, Subtract, Multiplication, Division, mRemainder, decimal, add_sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
num_input = findViewById(R.id.num_input);
num_output = findViewById(R.id.num_output);
num_backspace = findViewById(R.id.num_backspace);
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
//TODO: the backslash code goes here.
});
}
}
I tried doing this👇🏻
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
input = Float.parseFloat(num_input.getText() + "");
String sample_input = Float.toString(input);
sample_input = sample_input.substring(0,sample_input.length() - 1);
});
Some help would be great!
thanks in advance
It's better to store input as a String, not float. Because before you start doing mathematical calculations it's just a String input, and "backspace" means basically removing one character, it's not a mathematical operation. So, provided input is a String, backspace code will be:
input = input(0, input.length() - 1);
num_input.setText(input);
And before doing calculations convert your String input into float via
float operand = Float.parseFloat(input);
Put this code inside your setOnClickListener
String value = num_input.getText().toString();
if (value != null && value.length() > 0 ) {
value = value.substring(0, value.length() - 1);
}
num_input.setText(value);
How this is usually done is getting the current value (entered number) in the TextView, remove the last character from the string and writing it back to the TextView.

Change value of TextView in Android

I would like to change a TextView as a user adds things to a cart. The initial value is 0.00 and as the user adds items, this is added to the value. I have an AlertDialog that pops up when clicking a button that allows the user to choose an item.
My issue is a java.lang.StringToReal.invalidReal error. I think that I may not be getting the value of the TextVeiw properly but am not totally sure.
Thanks to anyone looking at this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.pickItem);
builder.setItems(R.array.items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
CartItems ci = new CartItems();
ci.setItem(which);
ci.setPrice(which);
cart.add(ci);
totalPriceTV = (TextView)findViewById(R.id.textView2);
double totalPrice = Double.parseDouble(totalPriceTV.toString());
totalPrice += ci.getPrice();
String newTotal = new Double(totalPrice).toString();
totalPriceTV.setText(newTotal);
}
});
builder.create();
builder.show();
}
});
}
In this line
double totalPrice = Double.parseDouble(totalPriceTV.toString());
Change totalPriceTV.toString() to totalPriceTV.getText().toString() and try again.
In order to change the text of a TextView in Android just use the ordinary geters and setters:
TextView.getText();
TextView.setText("text");
Since you deal with numbers i suggest you to use DecimalFormat when parsing a double to string. You can easily define the format of the number (i.e the number of digits after comma or the separator characters)
DecimalFormat df = new DecimalFormat("###,###.00");
String price = df.parse(someDouble);
textView.setText(price);
For these numbers: 234123.2341234 12.341123 the DecimalFormat would give you the following result:
234,123.23 and 12.34
Taken from page: http://developer.android.com/reference/android/view/View.html#toString()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
As a result you should use getText();
ie:
totalPriceTV.getText()
Just use totalPriceTV.setText(""+totalPrice);
or
totalPriceTV.setText(String.valueOf(totalPrice));

ArrayIndexOutOfBoundsExecption:Android

I am a newbie Android Developer. I am trying to get a text input from user using and Edittext box and then convert that text into string and then into a char array of size 4. i have an array already stored that is of size 4 and it contains values. i want to compare both the arrays and perform a task based on the result.
I don't know why am i getting the ArrayIndexOutOfBoundsExecption
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newgame);
Button submit = (Button) findViewById(R.id.guess);
EditText guess = (EditText) findViewById(R.id.editText1);
boolean c=false;
char[] guessword;
char[] appword = {'T', 'R', 'U', 'E'};
guessword = guess.getText().toString().toCharArray();
for(int i=0;i<appword.length;i++)
{
if(guessword[i]==appword[i])
{
c=true;
}
else
{
c=false;
}
}
final boolean correct=c;
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(correct){
startActivity(new Intent(Newgame.this, Win.class));
}
else{
startActivity(new Intent(Newgame.this, Loose.class));
}
}
});
}
}
The problem is that guessword may have fewer than four characters, and your code does not check for that condition.
Change your code as follows to account for this condition:
for(int i=0;i<appword.length;i++)
{
if((i < guessword.length) && (guessword[i]==appword[i]))
{
c=true;
}
else
{
c=false;
break; // <<<=== Add this to end the loop
}
}
Also note that your code as written does not "lock in" the false when characters are not equal to each other: for example, {'A','B','Z'} and {'X', 'Y', 'Z'} will compare equal under your old algorithm. Add break to exit the loop as soon as you see a false.
This is because you are going with the index from 0 to the value of the appword.
Take for example the case in which the user types in: "NO". Because you are iterating over appword which has the length greater than your actual text, when you do a guessword[i] it will crash throwing your IndexOutOfBoundsException.
I am not sure why you are using char[]. As I can see, for your example, String could solve the problems.
String appword = "TRUE";
String guessword = guess.getText().toString();
Then, the method that shows if the 2 are equal is :
if (appword.equals(guessword))
If you also want to match the case, use equalsIgnoreCase instead.
guessword is null when you walk over the first time (which happens in the onCreate). One thing you could do is change
if(guessword[i]==appword[i])
to
if(guessword != null && guessword.length =< i && guessword[i]==appword[i])
If you just want to compare the entered text to "TRUE", you can simply do:
String guessword = guess.getText().toString();
if ("TRUE".equals(guessword)) {
...
}

how do you call a value entered in a UI to your java class?

Making a simple app for my android.
in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"
how do I call the value of input1 in java and then perform a calculation on it?
For example...
suppose input1 = x
x + 5 or x*2
and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?
In the Activity where you are using this layout XML, you would do this:
private EditText input;
private EditText result;
public void onCreate(Bundle b) {
setContentView(R.layout.my_activity);
// Extract the text fields from the XML layout
input = (EditText) findById(R.id.input1);
result = (EditText) findById(R.id.result);
// Perform calculation when input text changes
input.addKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation() {
// Get entered input value
String strValue = input.getText().toString;
// Perform a hard-coded calculation
int result = Integer.parseInt(strValue) * 2;
// Update the UI with the result
result.setText("Result: "+ result);
}
Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.
In your XML you can also set android:inputType="number" to only allow numbers as entries.

Categories

Resources