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;
Related
Like the caption said the method "scanInput1" runs two times in a row when it should only run once. Then the method "arrayskapare" runs as intended but after that. instead of running the method "medelvarde" is jumps back and runs "scanInput1" again and again and again
import java.util.*;
class Heltalshanterare{
private static String scanInput1(){
System.out.print("Skriv in antal heltal: ");
Scanner scr = new Scanner(System.in);
String antalHeltal = scr.next();
try {
Integer.parseInt(antalHeltal);
}
catch (NumberFormatException e) {
System.out.println("Ogilitigt värde");
scanInput1();
}
return antalHeltal;
}
private static List<Integer> arrayskapare() {
int antalangivnatal = Integer.parseInt(scanInput1());
int noll = 1;
int heltal = 0;
String tal1 = "";
Scanner tal = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
while (noll <= antalangivnatal) {
noll++;
heltal++;
System.out.print("ange heltal " + heltal + ": ");
tal1 = tal.next();
try {
int num = Integer.parseInt(tal1);
list.add(num);
} catch (NumberFormatException e) {
System.out.println("Ogiltigt värde");
noll--;
heltal--;
}
}
return list;
}
public static int medelvarde(){
int antalsiffror = arrayskapare().size();
int sum = 0;
for (int i : arrayskapare()){sum += i;}
int medelvärde = sum / antalsiffror;
System.out.println("medelvärdet av dina tal är " + medelvärde);
return medelvarde();
}
public static void main(String [] args){
scanInput1();
arrayskapare();
medelvarde();
}
}
Im sorry that the code is so long but I have been struggling with this for too long and I really need some help.
Your main method is calling each method just once, which is what you need. But it's not actually holding onto any of the values being returned. So the number of heltal (integers in English) is captured from the user but then never actually stored anywhere. And later an array of numbers is captured but not stored anywhere.
Your second, bigger problem is that your methods are then calling the earlier methods all over again. So instead of asking the user to type in the data just once, you're forcing them to answer the exact same questions multiple times.
A much tidier approach is to alter your methods so that they take the required data as a parameter. Which means your arrayskapare (array producer) method should take the antalHeltal (number of integers) value as a parameter, and then it won't need to call the scanInput1 method again. Same thing can be done for your medelvarde (mean value) method: have it take the array as a method parameter, so that it won't need to call arrayskapare.
With those changes your main method can simply look like this:
public static void main(String [] args){
int antalHeltal = scanInput1();
List<Integer> heltalArray = arrayskapare(antalHeltal);
int medelvardet = medelvarde(heltalArray);
System.out.println("Medelvärdet är " + medelvardet);
}
Now each method just gets called once and the data captured from the user gets stored into variables and passed along the river of methods until the final result is reached.
i am doing an exercise to create a simple calculator in java.
i want the calculator to keep taking numbers after the equal sign is pressed. so if i press "10+10 =" the result will be 20, and if I want to press "+1 = " and the result will be 21. or if I want to subtract as well.
my code is below. im sure the change has to be made to the "equals" portion of the code but i am unsure where/how to begin.
public int getDisplayValue()
{
return displayValue;
}
public void numberPressed(int number)
{
currentValue = (currentValue * 10) + number;
displayValue = currentValue;
}
private void applyPreviousOperation()
{
if (previousOp == '+')
{
heldValue = heldValue + currentValue;
displayValue = heldValue;
}
else if (previousOp == '-')
{
heldValue = heldValue - currentValue;
displayValue = heldValue;
}
else {
heldValue = currentValue;
}
}
public void plus()
{
applyPreviousOperation();
previousOp = '+';
currentValue = 0;
}
public void minus()
{
applyPreviousOperation();
previousOp = '-';
currentValue = 0;
}
public void equals()
{
applyPreviousOperation();
previousOp = ' ';
currentValue = 0;
heldValue = 0;
}
public void clear()
{
displayValue = 0;
previousOp = ' ';
}
}
You need to define your question more clearly.
what's the calculator flow should be. You describe an operation that contradicts a simple a+b.
It really matters how you input the numbers, If for example the very first operation is texted "a+b" ,"a-b" .... than you can keep it as currentValue.
than next opperations will be calculated against currentValue.
Have a variable called defaultOperand. When the equals button is pressed, update the defaultOperand variable with the output of the operation. It becomes the default left side operand. If an operation is inputted without a left side operand, then use the value in the defaultOperand as the default left hand operand.
I'm currently "learning" JavaScript + Android Studio for school and I got a little problem for which I can't find the right answer on Google:
I want to know if an int variable has a specific number, for example, I'm looking for the number 7 now int numberOne = 25824 doesn't have a 7 inside, but int numberTwo = 12387 does have one. Is there a way to search for a specific number in int variables?
I tried converting the int into a new string variable, but somehow this doesn't work :(
Here's some code I'm working with:
public int round = 1;
public String nummerSieben = "" + round;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (round % 7 == 0 || nummerSieben.contains("7")==true) {
....
} else {
....
}
}
});
Thank you for your help!
public int round = 1;
public String nummerSieben = "" + round; // nummerSieben is now "1"
You're hard-coding the value of nummberSieben. You need presumably get some value from the view, and test that. If you get it as in int, use
Integer.toString(i).contains("7") // i is whatever number you get from your view.
If you get it as a String, then half the work is already done, and you just need
i.contains("7")
As noted above, this has nothing to do with JavaScript - both your example and my answer are in Java.
Couple of things:
Your comparison is not right, method String:contains() returns a boolean,
Module % does not assert you the number will contain 7 or one of it's multiples.
Integer.toString(value) converts easily your int to String.
Knowing this, you can do:
if (Integer.toString(round).contains("7")) {
// IT CONTAINS THE NUMBER!
} else {
// IT DOES NOT CONTAIN THE NUMBER
}
Here is perfect solution of your problem
public class Finder {
static int round = 123456789;
static String str = String.valueOf(round);
public static void main(String... args) {
if (str.contains("7")) {
System.out.println("Found");
} else {
System.out.println("Can't found...");
}
}
}
Just convert your integer to String and then try to found the specific value from that string.
You don't have to convert to string in order to search specific digit in integer.
You can use math for that purpose.
Here is the code:
private static boolean isFound(int round) {
while (round > 0) {
if (round % 10 == 7)
return true;
round /= 10;
}
return false;
}
basically what this code do is checking each last digit if it's equals to 7 if not he divides the num by 10 and remove the last digit and after checking again, it will do so until no digit left (num=0) or he will find 7.
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.
I am trying to create an application that returns a score based on user input.
for example if the user has 1000 posts on a specific site it would return 1. i would end it at 10000.
1000 = 1
2000 = 2 etc.
here is what i have so far and thanks. this site is awesome.
for now i just have each entry adding. value1+value2 etc.
public class DataIn extends Activity {
EditText editPostCount;
EditText editThanksCount;
EditText editRomCount;
EditText editThemeCount;
EditText editKernelCount;
EditText editTutorialCount;
EditText editYearsJoined;
Button mButton;
TextView results;
Button mButton1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.data_in);
android.app.ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
editPostCount = (EditText)findViewById(R.id.editPostCount);
editThanksCount = (EditText)findViewById(R.id.editThanksCount);
editRomCount = (EditText)findViewById(R.id.editRomThreads);
results = (TextView)findViewById(R.id.results);
editThemeCount = (EditText)findViewById(R.id.editThemeCount);
editKernelCount = (EditText)findViewById(R.id.editKernelCount);
editTutorialCount = (EditText)findViewById(R.id.editTutorialCount);
editYearsJoined = (EditText)findViewById(R.id.editYearsJoined);
mButton = (Button)findViewById(R.id.results_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
private void calculate() {
try {
Double value1 = Double.parseDouble(editPostCount.getText().toString());
Double value2 = Double.parseDouble(editThanksCount.getText().toString());
Double value3 = Double.parseDouble(editRomCount.getText().toString());
Double value4 = Double.parseDouble(editKernelCount.getText().toString());
Double value5 = Double.parseDouble(editThemeCount.getText().toString());
Double value6 = Double.parseDouble(editYearsJoined.getText().toString());
Double value7 = Double.parseDouble(editTutorialCount.getText().toString());
//do the calculation
Double calculatedValue = (value1+value2+value3+value4+value5+value6+value7);
//set the value to the textView, to display on screen.
results.setText(calculatedValue.toString());
} catch (NumberFormatException e) {
// EditText EtPotential does not contain a valid double
}
mButton1 = (Button)findViewById(R.id.clear_button);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editPostCount.setText("");
editThanksCount.setText("");
editRomCount.setText("");
editThemeCount.setText("");
editKernelCount.setText("");
editTutorialCount.setText("");
editYearsJoined.setText("");
results.setText("");}
});
} }
You can get the score for every value using a simple division, that is cut to an integer.
In this example I also defined one constant to determine for each different value a specific score factor.
private static final int TOTALCOUNT_SCOREFACTOR = 1000;
int totalCountScore = totalCount / TOTALCOUNT_SCOREFACTOR;
I suggest you not to use doubles, generally int is enough.
I also suggest you to use an array of values, instead of defining all of them separately. In that way, you can easily add or remove values in future.
I hope I am not misunderstanding your question, but if you want the score to add 1 point for every 1000 posts, you simply get the number of posts and divide by 1000. for example:
//value1 is the post count
int calculatedvalue = value1/1000;
So if the number of posts(value1) is 3500, calculatedvalue would be 3.(the remainder is cut off during division)