Using eclipse, first of all. I'm building an Android calculator. I have all my code, except there's a problem. One of my variables is not being used. My total1 variable is basically the counter for the program. When I add two numbers up and press equals, it always prints "0.0" and that's the value of total1. That means for some reason, it never changed throughout the whole program. I even tested this by using a print statement. I changed the value of total1 and it would print that value I assigned it to. What could be the problem?
public class HelloAndroidActivity extends Activity {
public EditText display;
String display1;
double displayValue;
// Program is printing out total1, as if it weren't maninpulated in the code
double total1 = 0.0;
double total2 = 0.0;
char theOperator;
public String buttonText;
public Button ButtonAdd, ButtonEqual, ButtonMultiply, ButtonDivide, ButtonMinus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (EditText) findViewById(R.id.editText1);
// Could it have something to do with this if statement?
if (display.length() != 0) {
display1 = display.getText().toString();
displayValue = Double.parseDouble(display1);
}
}
//Get the operator of the multiply, divide, subtract, add buttons when they are clicked and then do the following
public void getOperator(String btnText) {
theOperator = btnText.charAt(0);
total1 += displayValue;
display.setText("");
}
// Display a string in the box when a number button is clicked
public void onClick(View v) {
switch (v.getId()) {
case R.id.bOne:
display.append("1");
break;
case R.id.bTwo:
display.append("2");
break;
case R.id.bThree:
display.append("3");
break;
case R.id.bFour:
display.append("4");
break;
case R.id.bFive:
display.append("5");
break;
case R.id.bSix:
display.append("6");
break;
case R.id.bSeven:
display.append("7");
break;
case R.id.bEight:
display.append("8");
break;
case R.id.bNine:
display.append("9");
break;
case R.id.bZero:
display.append("0");
break;
case R.id.bPoint:
display.append(".");
break;
case R.id.bClear:
total2 = 0.0;
display.setText("");
break;
case R.id.bAdd:
buttonText = "+";
ButtonAdd = (Button) findViewById(R.id.bAdd);
ButtonAdd.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bMinus:
buttonText = "-";
ButtonMinus = (Button) findViewById(R.id.bMinus);
ButtonMinus.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bMultiply:
buttonText = "*";
ButtonMultiply = (Button) findViewById(R.id.bMultiply);
ButtonMultiply.setText(buttonText);
getOperator(buttonText);
break;
case R.id.bDivide:
buttonText = "/";
ButtonDivide = (Button) findViewById(R.id.bDivide);
ButtonDivide.setText(buttonText);
getOperator(buttonText);
break;
// Here's the equals button. When I click it it prints out "0.0", the value of total1, instead of adding the total below
case R.id.bEqual:
switch (theOperator) {
case '+':
total2 = total1 + displayValue;
break;
case '-':
total2 = total1 - displayValue;
break;
case '*':
total2 = total1 * displayValue;
break;
case '/':
total2 = total1 / displayValue;
break;
}
display.setText(Double.toString(total2));
total1 = 0.0;
break;
}
}
}
You are trying to add displayValue in your get operator method but you have not changed this value. You should be paring this value from the display before adding it to total1 It should be like this:
public void getOperator(String btnText){
theOperator = btnText.charAt(0);
total1+=Double.parseDouble(display.getText().ToString());
display.setText("");
}
Or like this if you need to save the current display value:
public void getOperator(String btnText){
theOperator = btnText.charAt(0);
displayValue = Double.parseDouble(display.getText().ToString());
total1+=displayValue;
display.setText("");
}
I see only one location where your total1 variable is modified, and there it has the value of displayValue added to it. displayValue is only modified once, in your onCreate method (called just once per Activity lifecycle) where it is loaded from the contents of the editText1 control (which we don't have the source for).
So in short I'm not surprised total1 is not being modified. It's a matter of checking the whole logic flow of your app.
Related
I'm trying to show the price and numbers in a list with toast. the app runs and works, but when I'm tap the submit button to check out the prices it closes.
before these codes below, everything works. so I know the problem is here but don't understand where...
public void onclick(View view){
SparseBooleanArray checked = listView.getCheckedItemPositions();
int num=0;
int sum=0;
for (int i = 0; i < listView.getAdapter().getCount() ; i++) {
if (checked.get(i)) {
num++;
switch (i){
case 0:
sum+=60;
break;
case 1:
sum+=46;
break;
case 2:
sum+=36;
break;
case 3:
sum+=34;
break;
case 4:
sum+=19;
break;
case 5:
sum+=5;
break;
case 6:
sum+=3;
break;
}
String s="";
s="you selected: "+ Integer.toString(num)+ "items";
s+="\n\r";
s+="price is: "+ Integer.toString(sum)+ "toman";
Toast.makeText(MainActivity.this,s, Toast.LENGTH_SHORT).show();
}
}
}
}
sum all price in onBindviewHolder and toast it when you have last time created
sum += price;
if(isLastItem){
Toast.makeText(MainActivity.this,sum, Toast.LENGTH_SHORT).show();}
I worked on a simple calculator app that does not pile up an expression like google calculator. Instead it stores the result in an operand when an operation button is pressed and so it does not follow BODMAS precedence rules. Like if I perform 2 + 2 / 2 I get 4 as the result whereas the result should be 3 as the division is performed first
Is there a way to take input as a whole expression and then evaluate it collectively?
Are there any predefined classes that I can use that are included in java?
The code for the onClickListeners of operators and calculation performing function is:
View.OnClickListener opListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button b = (Button) view;
String op = b.getText().toString();
String value = newNumber.getText().toString();
try {
Double doubleValue = Double.valueOf(value);
performOperation(doubleValue, op);
} catch (NumberFormatException e) {
newNumber.setText("");
}
pendingOperation = op;
displayOperation.setText(pendingOperation);
}
};
private void performOperation(Double value, String operation) {
if (operand1 == null) {
operand1 = value;
} else {
if (pendingOperation.equals("=")) {
pendingOperation = operation;
}
switch (pendingOperation) {
case "=":
operand1 = value;
break;
case "/":
if (value == 0) {
operand1 = 0.0;
Toast.makeText(this,"Cannot Divide By Zero, Resetting value to zero",Toast.LENGTH_LONG).show();
} else {
operand1 /= value;
}
break;
case "*":
operand1 *= value;
break;
case "+":
operand1 += value;
break;
case "-":
operand1 -= value;
break;
}
}
result.setText(operand1.toString());
newNumber.setText("");
}
I use switch statement in Java and once the program reaches the break statement, instead of exiting the switch it moves to the last row of the switch body and executes it as well.
I have tried it in Debug mode writing in the console "Sofia" and 250. It enters the first switch, finds the "Sofia" case, assigns value to the commission variable, executes the break and than goes to the last row of the switch body and executes the return as well. If I delete the default case altogether, after executing the break it again goes to the last row of the body and executes the break from the third case. Regardless of what I try, executing the break does not seem to exit the body of the switch body and always goes to it's last row.
Do you have any idea why that might be? Here is the code:
package SlojniLogicheskiProverki;
import java.util.Scanner;
public class Zadacha {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String city = scan.nextLine();
double sales = Double.parseDouble(scan.nextLine());
double commission = 0;
if (sales >= 0 && sales <= 500) {
switch (city) {
case "Sofia":
commission = 5;
break;
case "Plovdiv":
commission = 5.5;
break;
case "Varna":
commission = 4.5;
break;
default:
System.out.println("error");
return;
}
} else if (sales > 500 && sales <= 1000) {
switch (city) {
case "Sofia":
commission = 7;
break;
case "Plovdiv":
commission = 8;
break;
case "Varna":
commission = 7.5;
break;
default:
System.out.println("error");
return;
}
} else if (sales > 1000 && sales <= 10000) {
switch (city) {
case "Sofia":
commission = 8;
break;
case "Plovdiv":
commission = 12;
break;
case "Varna":
commission = 10;
break;
default:
System.out.println("error");
return;
}
}
else if (sales > 10000) {
switch (city) {
case "Sofia":
commission = 12;
break;
case "Plovdiv":
commission = 14.5;
break;
case "Varna":
commission = 13;
break;
default:
System.out.println("error");
return;
}
} else {
System.out.println("error");
return;
}
System.out.printf("d%",commission);
}
}
I am converting a roman numeral input to it's integer value. In my convertChar method, I keep getting an error that it is an unreachable statement whenever I add a break statement in to the code. I don't know why this is. I'm a new student and I must have done something wrong and I was hoping maybe someone can show me what I did wrong and how to fix it. It must have something to do with the way I set the methods up right? I still get confused on what variables to input so maybe I messed up there but I'm not experienced enough to know exactly what I did wrong. Here is everything I have:
public class RomanNumeralConverter {
public int romanInput() {
return convert(getUserInput());
}
public String getUserInput() {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral in uppercase: ");
String userInput = numberInput.next();
numberInput.close();
return userInput;
}
public int convert (String userInput) {
int result = 0;
int subtractamount = 0;
int x = userInput.length();
while(x != 0) {
char romanConvert = userInput.charAt(x);
if(x >= 1) {
if(convertChar(romanConvert) >= convertChar(userInput.charAt(x - 1))) {
subtractamount += convertChar(userInput.charAt(x - 1));
}
}
result += convertChar(romanConvert);
x--;
}
result -= subtractamount;
return result;
}
public static char convertChar(char value) {
switch (value) {
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
System.out.println("Invalid character!");
return 0;
break;
}
return value;
}
public void printValue() {
System.out.println(romanInput());
}
public static void main(String[] args) {
new RomanNumeralConverter().printValue();
}
}
Your problem lies in your switch statement. You can minimize this occurring elsewhere by attempting to have methods return only once (which i think is best practice)
public static char convertChar(char value) {
char result;
switch (value) {
case 'I':
result = 1;
break;
case 'V':
result = 5;
break;
case 'X':
result = = 10;
break;
case 'L':
result = 50;
break;
case 'C':
result = 100;
break;
case 'D':
result = 500;
break;
case 'M':
result = 1000;
break;
default:
System.out.println("Invalid character!");
result = 0;
break;
}
return result
}
In Java, it is a compile error to have statements that will never be reached while execution. In your case, the break statement will never be reached as there is a return statement above it. Also that last return statement will never be reached as you already would have returned in any case by the end of the switch block.
The problem is in your switch statement.
A default case can be thought of like the else in an if-else statement; it will always execute if no other condition in the switch is satisfied. If you are performing a return (or throw) inside of a default case, any code that follows after that will not be reachable.
You have two options:
Change the return statements to only assign a value to result instead, meaning that there's only one point of return from your code, or
Remove the return result from after your switch.
I developed an app.. it is a numerology app.. where user's firstname, second name and third name is collected and calculated... values from 1 -9 are assigned for each values and when calculating these value for all letters has to be added together and make into a one digit 1 - 9. after that this value is given to textview in another activity and the result is displayed.... my problem is i did the programming .. but when adding .. correct value is not displaying.. i used switch case for giving values for each letter... i gave 0 as default value.. when result is displayed the value is displaying as 0 . if i change it to 1 then 1 is added to the value and that value is isplaying.. please check my code and if ther any mistake pls point it out 4 me... thanks...
MainActivity.java
public void gReport(View V)
{
long sum1 = 0;
long sum2 = 0;
long sum3 = 0;
long sum7 = 0;
long sum8 = 0;
long sum9 = 0;
long sum10 = 0;
EditText et1 = (EditText) findViewById (R.id.editText1);
EditText et2 = (EditText) findViewById (R.id.editText2);
EditText et3 = (EditText) findViewById (R.id.editText3);
EditText et7 = (EditText) findViewById (R.id.editText7);
EditText et8 = (EditText) findViewById (R.id.editText8);
EditText et9 = (EditText) findViewById (R.id.editText9);
sum1 = getSum1(et1.getText().toString());
sum2 = getSum2(et2.getText().toString());
sum3 = getSum3(et3.getText().toString());
/*sum7 = getSum7(et7.getText().toString());
sum8 = getSum8(et8.getText().toString());
sum9 = getSum9(et9.getText().toString());*/
sum10 = getSum10 (et1.getText().toString() + et2.getText().toString() + et3.getText().toString());
Intent i = new Intent(this, FirstResult.class);
i.putExtra("name10", sum10 + "");
startActivity(i);
}
private long getSum10(String text)
{
long sum10 = 0;
char[] name10 = new char[text.length()];
name10 = text.toCharArray();
for(int i=0; i<text.length(); i++)
{
sum10 += value10( name10[i] );
}
while (sum10>9)
{
sum10 = findDigitSum10(sum10);
}
return sum10;
}
private long value10(char a)
{
switch(a)
{
case 'A':
return 1;
case 'B':
return 2;
case 'C':
return 3;
case 'D':
return 4;
case 'E':
return 5;
case 'F':
return 6;
case 'G':
return 7;
case 'H':
return 8;
case 'I':
return 9;
case 'J':
return 1;
case 'K':
return 2;
case 'L':
return 3;
case 'M':
return 4;
case 'N':
return 5;
case 'O':
return 6;
case 'P':
return 7;
case 'Q':
return 8;
case 'R':
return 9;
case 'S':
return 1;
case 'T':
return 2;
case 'U':
return 3;
case 'V':
return 4;
case 'W':
return 5;
case 'X':
return 6;
case 'Y':
return 7;
case 'Z':
return 8;
default:
return 0;
}
}
private long findDigitSum10(long n)
{
int sum10=0;
while (n != 0)
{
sum10 += n % 10;
n = n / 10;
}
return sum10;
}
}
ResultActivity.java
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.firstresult_xm);
TextView txt1 = (TextView) findViewById (R.id.textView2);
txt1.setText(getIntent().getStringExtra("name10"));
}
you have no key sum10 inside your intent, but only name10. You should see the String int first TextView and nothing in the second one
May be encoding in eclipse is different that Android? Try to change it to UTF-8 in propreties of project.
I tried such concole code. Your function of value10 works correctly.
public class HelloWorld {
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
long a = hw.value10('F');
System.out.println("val: " + a);
}
private long value10(char a)
{
// TODO Auto-generated method stub
switch(a)
{
case 'A':
return 1;
case 'B':
return 2;
case 'C':
return 3;
case 'D':
return 4;
case 'E':
return 5;
case 'F':
return 6;
case 'G':
return 7;
case 'H':
return 8;
case 'I':
return 9;
case 'J':
return 1;
case 'K':
return 2;
case 'L':
return 3;
case 'M':
return 4;
case 'N':
return 5;
case 'O':
return 6;
case 'P':
return 7;
case 'Q':
return 8;
case 'R':
return 9;
case 'S':
return 1;
case 'T':
return 2;
case 'U':
return 3;
case 'V':
return 4;
case 'W':
return 5;
case 'X':
return 6;
case 'Y':
return 7;
case 'Z':
return 8;
default:
return 0;
}
}
}