How to make my android calculator working - java

I am making a basic calculator for Android in Java. I am stuck in one final step where it must add the input with the previous input. Have a look at the code:
public void displayValue(){
String mything = display.getText().toString();
input = Integer.parseInt(mything);
}
public void number1(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(1));
displayValue();
}
public void number2(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(2));
displayValue();
}
public void plus(View view){
displayValue(); //result= 0
result = result + input; //result= input
input = 0; //input=0
//in this step input becomes 0 to let the user enter new number input but this
//input never add the old result and the equal shows the old result.
}
public void equal(View view){
displayValue();
display.setText(Integer.toString(result));
}
I noticed that if I add a line in equal method and add the result to input I get the correct answer but that's not gonna be helpful as there will be minus button too.
Any ideas?
Thanks.

It's definitely hard to tell because you don't include full code, which would be helpful, but could it be because you call displayValue(); in some places before doing the math? Specifically in the plus method.

Ok finally I came up with a solution.
As the only option for calculation of result and new input is in equal method (because logically when user press the equal button, so wants to ends the equation), so I added two boolean values for each minus and plus calculation. Then I added both calculation for adding or minus 2 values.
Then when the user inter first part of the calculation and then hit plus sign, the boolean value of plus becomes true and after entering new input and hitting the equal sign, it does the true part of the calculation. Well it is a bit hard to explain but i guess by looking at the code you would get what I mean.
boolean whenMinus = false;
boolean whenPlus = false;
public void plus(View view){
displayValue();
result = input;
input = 0;
whenPlus = true;
}
public void minus(View view){
displayValue();
result = input;
input = 0;
whenMinus = true;
}
public void equal(View view){
if (whenPlus == true){result = result + input; whenPlus = false;}
if (whenMinus == true){result = result - input; whenMinus = false;}
display.setText(Integer.toString(result));
}
I am not sure if it is the correct way of making this calculator. But I fixed my problem anyway. It would be great to comment me and let me know if it is the standard way or its kinda hacking. I am not a pro anyway.

Related

Checking which button user pressed and checking the button text

I am a noob in Java and programing and I am making an app where the user is trying to guess a city based on a picture. The user sees a picture of the city and has three buttons under the picture with different answers in them. The pictures are randomized from an array and the buttons text changes so that atleast one of the buttons has the correct answer. I want a TextView with "correct" to show if user is correct and one with "incorrect" to show if user is wrong. The text is showing up when pressing any button and not when the button with the correct text is pressed. So this is what I have tried and am stuck on. And yes I know I have many mistakes in my code, such as names of methods and so. I will change these later.
I have three booleans that are set to false, they are representing which button is pressed. You will understand more later.
Boolean test1 = false;
Boolean test2 = false;
Boolean test3 = false;
In main i have three buttons and they all call on the checkanswer function. Also they all turn their own boolean to true there, which u will se why soon. Example of one of the buttons.
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
test1 = true;
checkanswer();
}
});
So here is the checkanswer function
public void checkanswer() {
DisplayRandomImage();
//Giving three strings random city names from the "cities" array.
Random rndBtnTxt = new Random();
String randomCity1 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity2 = cities[rndBtnTxt.nextInt(cities.length)];
String randomCity3 = cities[rndBtnTxt.nextInt(cities.length)];
//Setting the random city names to the three different buttons.
btn1.setText(randomCity1);
btn2.setText(randomCity2);
btn3.setText(randomCity3);
//takes the picked image from the "DisplayRandomImage" method.
String str = String.valueOf(pickedImg);
//Tells what to call the different pictures, they are known as numbers make sure they are given names instead.
if (pickedImg == 0)
str = "venice";
if (pickedImg == 1)
str = "new york";
//If-statement checking so that atleast one button has the correct answer.
if (randomCity1 != str || randomCity2 != str || randomCity3 != str) {
Random rndbtn = new Random();
Button x = btnArray.get(rndbtn.nextInt(btnArray.size()));
//Sets one of the three buttons so that it has the correct answer.
x.setText(str);
}
//See where the correct answer is
String buttonText1 = btn1.getText().toString();
String buttonText2 = btn2.getText().toString();
String buttonText3 = btn3.getText().toString();
//check if the button that the user pressed has the correct answer
if (test1.equals(true) && buttonText1.equals(str)){
CorrectAnswer();
test1 = false;
}
if (test2.equals(true) && buttonText2.equals(str)){
CorrectAnswer();
test2 = false;
}
if (test3.equals(true) && buttonText3.equals(str)){
CorrectAnswer();
test3 = false;
}
else
WrongAnswer();
}
I am not sure what I am doing wrong here. For example the "test1" is set to True when I press "btn1" and if "buttontext1" equals to the same as "str" does it should work. But for some reason it seems randomised which of the three buttons calls for the CorrectAnswer method. What am I doing wrong here?
Can we see CorrectAnswer? Also,
right off the bat, I noticed that instead of using test1, test2 and test3 to indicate which button was pressed, you can just pass some sort of argument into checkAnswer, like int button.
So onClick would look like this for the first button, and subsequent buttons by incrementing the 1:
public void onClick(View v) {
checkanswer(1);
}
and checkanswer would look like this:
public void checkanswer(int button) {
... (previous stuff) ...
//check if the button that the user pressed has the correct answer
if (button == 1 && buttonText1.equals(str)){
CorrectAnswer();
}
if (button == 2 && buttonText2.equals(str)){
CorrectAnswer();
}
if (button == 3 && buttonText3.equals(str)){
CorrectAnswer();
}
else
WrongAnswer();
}
So try this out.
Its pretty hard to tell where the bug is, if you only show us pieces of the full code.
Mistakes could be e.g. in CorrectAnswer()...
I would recommend binding onlick-listeners to your buttons instead of changing booleans.
Check this out here: https://developer.android.com/reference/android/widget/Button
Additionally I noticed another mistake:
randomCity1 != str || randomCity2 != str || randomCity3 != str
This will return true if at least one of the Strings does not contain the right answer
You probably want to enter the if-Statement, when there isnt already a button with the correct answer.This is what you would like to use:
randomCity1 != str && randomCity2 != str && randomCity3 != str
EDIT: Check out the answer of Barcode for another example of using onClicklisteners.
Thank you both for answering the question, i have found a way to complete this problem:
public void testingMethod(int button){
switch(button){
case 1:
if (buttonText1 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 2:
if (buttonText2 == str)
CorrectAnswer();
else
WrongAnswer();
break;
case 3:
if (buttonText3 == str)
CorrectAnswer();
else
WrongAnswer();
break;
}
}
And since you were wondering how the method CorrectAnswer looked like here it is, yes I know it's probably unnecessary having this method but I am noob after all.
public void CorrectAnswer() {
findViewById(R.id.txtIncorrect).setVisibility(View.GONE);
findViewById(R.id.txtCorrect).setVisibility(View.VISIBLE);
}

while loop inside for loop, confused?

Completely new to programming, and I was doing a project and I am confused on how I can make it work. Please help me
boolean answer1 = true;
for (int i=0;i<q.questionbank.length;++i)
{ q.Question = input(q.questionbank[i]);
while(answer1 == true)
{
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans))))
{
score = printquiz(answer,score,q.Question);
answer1 = false;
}
else
{
print("Not a Valid Answer, please try again\n");
}
}
}
return score;
Over here, I have a class called questionbank and quiz. The correctans/impossibleans/wrongans are part of the quiz data type. whereas the q.question is part of questionbank. I have some question on an array in the questionbank data type. I want to use for loop to go through the questions and if the user input the correct answer, there score goes up. It works for the first question but doesnt for the second question. usually when they answer correctly, I have another method printquiz that has decision statements to tell the user if their answer is correct or wrong, and assign them points. but its not even going to that method after the first iteration of the loop. I am confused on what is going on. Please help me
This is how I would have set it up. Assume the answer to be false until you get one. Then set it to true to exit the loop.
for (int i = 0; i < q.questionbank.length; ++i) {
q.Question = input(q.questionbank[i]);
answer1 = false;
while (!answer1) {
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans)))) {
score = printquiz(answer, score, q.Question);
answer1 = true;
} else {
print("Not a Valid Answer, please try again\n");
}
}
}
The second time doesn't work, because you set answer1 to false and never set it back to true again. So the while loop is not being entered anymore (= doesn't evaluate to true anymore) after the answer1 = false line of code in the if statement has been reached the first time.
To fix this, try to put answer1 = true inside the for loop, before the while loop.

How to know if JRadioButton is enabled in java

So my argument in my if statement below has to check if my JRadioButton is checked, but for some reason, even if it's not checked, the program still runs.
public void actionPerformed(ActionEvent e) {
String actionCheck = Binary.userInput1.getText();
if(Binary.binary.isEnabled() && actionCheck.matches("[01]+")){ // checks if its binary
int decimalValue = Integer.parseInt(actionCheck, 2);
String convertedDecimal = Integer.toString(decimalValue);
Binary.userInput2.setText(convertedDecimal);
}
else if (Binary.decimal.isEnabled() && decimalCheck(Binary.userInput1)){
int binaryValue = Integer.parseInt(actionCheck);
Binary.userInput2.setText(Integer.toBinaryString(binaryValue));
}
else
Binary.userInput1.setText("WRONG INPUT! -- try again");
}
What am I missing?
The buttons are called binary and decimal (Yes i know, my class is called Binary also, newbie errors)
Answer was found!
It's not isEnabled() that should be used in this case but the method isSelected()
Try to use yourJRadioButton.isSelected() instead of isEnabled().

Given string will only print when boolean is false, not when true

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many of your two bosses are smiling?");
int smiles = in.nextInt();
final boolean trouble;
if(smiles == 0 || smiles == 2){
trouble = true;
}else if(smiles == 1){
trouble = false;
if(trouble == false){
System.out.println("The coast is clear!");
}
else if(trouble == true){
System.out.println("You're in trouble!");
}in.close();
}
This whole thing is stupid.
I need to basically make a boolean-using program that tells the user, via the number of bosses smiling, wether or not they are in trouble.
Both/Neither smiling = trouble
One smiling and the other not smiling = no trouble
But it will only print the given strings if there's no trouble.
I get that I'm a fukken idiot, and this whole task I'm required to do is, personally, kinda stupid. But whatever, moron can't do simple code. Maybe someone could tell me what stupid mistake I made so I can get this done and out of the way?
It's resolved, I'm an idiot who can't read the bracket placement/formatting properly. Also yes, it shouldn't have been a final, though changing that was not the resolution at first.
Change
final boolean trouble;
to
boolean trouble = false;
Your boolean value is final and thus cannot be modified, its default value is "false". That means that it is never changed from "false" no matter what happens next.
By the way, if a number larger than 2 is input, the boolean value will also be "false".
A check to see if the integer being input is in the right range (between 0 and 2) would be a good idea.

How do I use JOptionPane in a while loop?

The code segment below is a part of a bigger program, but I think this is where I'm having the issue. So, I am trying to use a while loop to ask for input over and over until the program is done, and the dialog box is not coming up and I don't know why. I would really appreciate it if someone could take a look and tell me what I'm doing wrong. If you want to see the entire program just tell me.
Code
boolean done = true;
while(!done)
{
Grid grid = new Grid();
boolean userDone = true;
int compRandom = (int) (Math.random() * 9) + 1;
String input1 = JOptionPane.showInputDialog("Please input a number 1-9 for where you would like to place your piece: ");
Integer input = Integer.parseInt(input1);
boolean done = true;
must be
boolean done = false;

Categories