Simple Java Calculator without limit of numbers to be operated - java

So I'm super new to programming and java, a colleague sent me this challenge to build a simple calculator with all four operation (+, - , / , *) but for only too integers.
Now he's asked me to remove this limit of only two values.
(i.e. 10+20+10+12 = 52 )
how difficult is that, should I be learning this right now ?
public class Calculadora {
private int numero1;
private int numero2;
private int resultado;
public int soma(){
this.setResultado(numero1 + numero2);
return this.resultado;
}
public static int soma(final int numero1, final int numero2){
return numero1 + numero2;
}
public int subtrai(){
this.setResultado(numero1 - numero2);
return this.resultado;
}
public static int subtrai(final int numero1, final int numero2){
return numero1 - numero2;
}
public int multiplica(){
this.setResultado(numero1 * numero2);
return this.resultado;
}
public static int multiplica(final int numero1, final int numero2){
return numero1 * numero2;
}
public int divisao(){
this.setResultado(numero1 / numero2);
return this.resultado;
}
public static int divisao(final int numero1, final int numero2){
return (numero1 / numero2);
}
public int getNumero1() {
return numero1;
}
public void setNumero1(int numero1) {
this.numero1 = numero1;
}
public int getNumero2() {
return numero2;
}
public void setNumero2(int numero2) {
this.numero2 = numero2;
}
public int getResultado() {
return resultado;
}
private void setResultado(int resultado){
this.resultado = resultado;
} ```

Check out varargs:
public Integer sum(Integer... numbers) {
int sum = 0;
for (Integer number : numbers) {
sum += number;
}
return sum;
}

I would look in to the following topics:
infix, postfix, prefix, and the Stack class. That is the essence of evaluating and
processing mathematical expressions of arbitrary length.

If you just use + or - look into ArrayList ArrList... you can add all your operands with ArrList.add( input integer here) an use a for loop to add them: for (into i=0;i<ArrList.length();i++) { result +=ArrList[i];} If you use / and × you would have to sort your operands after the weight of your operators:2+3+4×2 , to use a loop you would have to record it to: (.4×2)+3+2
Note: If, for my first case, you got like 3-4 you would ad them ad Arr[0]=3 and Arr[1]=-3.

Related

Different variable output from same method JAVA genetic algorithm

So i am trying to build a genetic algorithm on java i stuck on getting
fitness of my population here 3 classes from my project:
Class Individu
public class Individu {
int Popsize=4;
int Health[]= new int[Popsize];
int Attack[]= new int[Popsize];
int Atspeed[]= new int[Popsize];
int Move[]= new int[Popsize];
int health,attack,lifetime,dmgdone,attspeed,range,move;
double fitness;
double Pitness[]= new double[20];
Random random = new Random();
public int setHealth(){
health = random.nextInt(150 - 75) + 75;
return health;
}
public int setAttack(){
attack = random.nextInt(10 - 5) + 10;
return attack;
}
public int setAttspeed(){
attspeed = random.nextInt(3 - 1) + 3;
return attspeed;
}
public int setMoveSpeed(){
move = random.nextInt(8 - 4) + 1;
return move;
}
public int getGeneHealth(int index) {
return Health[index];
}
public int getGeneAttack(int index) {
return Attack[index];
}
public int getGeneAtspedd(int index) {
return Atspeed[index];
}
public int getGeneMove(int index) {
return Move[index];
}
public void setGene(int index, int value) {
Health[index]=value;
Attack[index]=value;
Atspeed[index]=value;
Move[index]=value;
fitness = 0;
}
public int size() {
return Popsize;
}
public double[] GenerateIndividual(){
for (int i = 0; i <Popsize; i++) {
Health[i]=setHealth();
Attack[i]=setAttack();
Atspeed[i]=setAttspeed();
Move[i]=setMoveSpeed();
}
return Pitness;
}
Class Fitness
public class Fitness {
Individu individu= new Individu();
double fitness;
double Pitness[]= new double[20];
public double getFitness(){
individu.GenerateIndividual();
for (int i = 0; i <=3; i++) {
fitness=
individu.getGeneHealth(i)+individu.getGeneAtspedd(i)+
individu.getGeneAttack(i)+
individu.getGeneMove(i));
fitness=fitness/171;
Pitness[i]=fitness;
System.out.println("Health from class
fitness"+individu.Health[i]);
}
return fitness;
}
}
Main Class
public class main {
public static void main(String[] args) {
Individu aaa=new Individu();
Fitness bbb= new Fitness();
bbb.getFitness();
aaa.GenerateIndividual();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
for (int i=0; i<=3; i++){
//System.out.println("Fitness ");
System.out.println("Generasi ke :"+i+1);
System.out.println("Health "+aaa.getGeneHealth(i));
System.out.println("Attackspeed "+aaa.getGeneAtspedd(i));
System.out.println("Attack "+aaa.getGeneAttack(i));
System.out.println("movementSpeed "+aaa.getGeneMove(i));
}
}
}
What i struggle is when i run this script i got 2 double value from 1 variable first value is from Fitness class as i printed here
System.out.println("Health from class fitness"+individu.Health[i]);
and second variable i printed here from Main Class
System.out.println("Health "+aaa.getGeneHealth(i));
that 2 variable is always have different value causing my fitness and my generation is not correlated each other.
My question is how to make this 2 variable print same value?
Well, aside from the many problems I can detect about the essentials of Genetic Algorithms, I see 'individu' and 'aaa' are two different Java objects.
Individu aaa=new Individu();
aaa.GenerateIndividual();
and
Individu individu= new Individu();
individu.GenerateIndividual();
Since your Health and Fitness are randomly generated on GenerateIndividual(), both 'aaa' and 'individu' will get different Health values.
I strongly recommend you to review GA essentials, since I can see many conception errors in your system.

simple objects and methods

Program is to add and average and list amount of times the "addNumber" method is called.
I can make the Amount work, but nothing else
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("Amount: " + stats.amountOfNumbers());
System.out.println("sum: " + stats.sum());
System.out.println("average: " + stats.average());
}
public class NumberStatistics {
private int amountOfNumbers;
private int addNumber;
private double average;
private int sum;
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;
}
public void addNumber(int number) {
number=addNumber;
addNumber++;
// code here
}
public int amountOfNumbers() {
return addNumber;
// code , here
}
public int sum() {
return this.addNumber++;
}
public double average() {
return sum() / addNumber;
}
My incorrect output:
Amount: 4
sum: 4
average: 0.0
Ok lets start with the constructor.
public NumberStatistics() {
this.amountOfNumbers=amountOfNumbers;
this.average=0;
this.sum=0;}
Here when you create an object you initialize average and sum to 0 but
this.amountOfNumbers=amountOfNumbers; has no particular effect.
To sum up what i think you wanted to do is something like this:
public NumberStatistics()
{
this.average = 0;//this keyword here is not needed but i used it since you did too
this.sum = 0;
this.amountOfNumbers = 0;
}
Then we go to this block of code here:
public void addNumber(int number) {
number=addNumber;
addNumber++;
}
Ok, this line makes no sense since you are setting the parameter equal to the addNumber variable which is something that does not help you at all, what i think you wanted to do here is the following:
public void addNumber(int number) {
sum += number;//same as sum = sum + number;
amountOfNumbers++;//same as amountOfNumbers = amountOfNumbers +1;
}
Then you need a method that returns the average like this:
public double average() {
return average = sum / amountOfNumbers; //i use the average variable only because you did,
//the most efficient way here is just to return sum / amountOfNumbers
}
Finally, the last two methods that i think you were trying to create are these:
public int amountOfNumbers() {
return amountOfNumbers;
}
public int sum() {
return sum;
}
This is my first post ever so i hope that it helps.
In NumberStatistics, you only need the count and a sum. You add to the sum with addNumber (and increment the count). Something like,
public class NumberStatistics {
private int count = 0;
private int sum = 0;
public void addNumber(int number) {
this.sum += number;
count++;
}
public int getCount() {
return count;
}
public int sum() {
return sum;
}
public double average() {
return sum() / (double) getCount();
}
}

Java Interfaces/Callbacks for Using 1 of 2 Possible Methods

I have read up on Java Interfaces (callbacks) because I was told by a professor I should use callbacks in one of my programs. In my code, there are two Mathematical functions I can 'pick' from. Instead of making a method activate() and changing the code inside (from one function to the other) when I want to change functions, he said I should use callbacks. However, from what I've read about callbacks, I'm not sure how this would be useful.
EDIT: added my code
public interface
//the Interface
Activation {
double activate(Object anObject);
}
//one of the methods
public void sigmoid(double x)
{
1 / (1 + Math.exp(-x));
}
//other method
public void htan(final double[] x, final int start,
final int size) {
for (int i = start; i < start + size; i++) {
x[i] = Math.tanh(x[i]);
}
}
public double derivativeFunction(final double x) {
return (1.0 - x * x);
}
}
If you want to use interfaces something like this would work.
I have a MathFunc interface that has a calc method.
In the program I have a MathFunc for mutliplication and one for addition.
With the method chooseFunc you can choose one of both and with doCalc the current chosen MathFunc will do the calculation.
public interface MathFunc {
int calc(int a, int b);
}
and you can use it like that:
public class Program {
private MathFunc mult = new MathFunc() {
public int calc(int a, int b) {
return a*b;
}
};
private MathFunc add = new MathFunc() {
public int calc(int a, int b) {
return a+b;
}
};
private MathFunc current = null;
// Here you choose the function
// It doesnt matter in which way you choose the function.
public void chooseFunc(String func) {
if ("mult".equals(func))
current = mult;
if ("add".equals(func))
current = add;
}
// here you calculate with the chosen function
public int doCalc(int a, int b) {
if (current != null)
return current.calc(a, b);
return 0;
}
public static void main(String[] args) {
Program program = new Program();
program.chooseFunc("mult");
System.out.println(program.doCalc(3, 3)); // prints 9
program.chooseFunc("add");
System.out.println(program.doCalc(3, 3)); // prints 6
}
}

Java passing int value/data

Can anyone see what is wrong with my code? I get 0 from return of the calculation.
Created a small calculation on second class and pass the result data to main class, then print.
main class
package javaapplication3;
public class JavaApplication3 {
public static void main(String[] args) {
cal bla = new cal();
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
}
second class
package javaapplication3;
public class cal {
public int total = 11;
public int count = 2508;
public int calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public int getRatio () {
return (calRatio);
}
}
PS: By changing bla.getRatio to bla.caln(); worked. I think I've got other projects mixed up. Thanks for the input guys.
You're doing integer division, which truncates the result to an integer.
You need to cast either operand to double.
bla.getRatio();
String dCount = String.valueOf(bla.getRatio());
You never call the caln()-method, so calRatio is 0 forever.
Maybe you meant the following:
bla.caln();
String dCount = String.valueOf(bla.getRatio());
Plus, you try to divide integers. Try this:
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
public double getRatio () {
return calRatio;
}
}
You never call the "setter" function caln(), so calRatio was never set. So it returns the 0 for calRatio.
replace
public void caln () {
calRatio = count / total;
System.out.print(calRatio);
}
by this
public cal () {
calRatio = count / total;
System.out.print(calRatio);
}
Try this:
public static void main(String[] args) {
cal bla = new cal();
bla.caln();
String dCount = String.valueOf(bla.getRatio());
System.out.print(dCount);
}
I get 0 from return of the calculation.
As you should. 11 / 2508 does an integer division which is 0
If you want a non-zero I suggest changing
public double getAverage () {
return (double) total / count;
}
Normally you divide the total by the count to get the average.
It will return 0, always, because you are returning an int type. The result of your division will always be some floating point value, so you need to store it as such, and return it.
public class cal {
public int total = 11;
public int count = 2508;
public double calRatio;
public void caln() {
calRatio = (double)count / (double)total;
System.out.print(calRatio);
}
}

Random math questions generator for Android

Any help or advice would be greatly appreciated. I'm trying to create a simple game which generates ten different, random questions. The questions can contain 2, 3 or 4 integers. So something like this: 55 2 − 4 − 101, 102/3/3, 589 − 281, 123 + 5 6 + 2.
The question will be displayed in a textview and then the user can take a guess, entering values into an edittext and then upon clicking a key on a custom keypad I have created it will check the answer, and then display the next question in the sequence of 10.
I know how to create random numbers, just struggling to work out how to create a whole question with random operators (+, -, /, *).
Big thank you to anyone who has the time to construct a reply.
A little of spare time produced a complete example for your case. Create new RandomMathQuestionGenerator.java file and it is cooked for compilation.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class RandomMathQuestionGenerator {
private static final int NUMBER_OF_QUESTIONS = 10;
private static final int MIN_QUESTION_ELEMENTS = 2;
private static final int MAX_QUESTION_ELEMENTS = 4;
private static final int MIN_QUESTION_ELEMENT_VALUE = 1;
private static final int MAX_QUESTION_ELEMENT_VALUE = 100;
private final Random randomGenerator = new Random();
public static void main(String[] args) {
RandomMathQuestionGenerator questionGenerator = new RandomMathQuestionGenerator();
List<Question> randomQuestions = questionGenerator.getGeneratedRandomQuestions();
for (Question question : randomQuestions) {
System.out.println(question);
}
}
public List<Question> getGeneratedRandomQuestions() {
List<Question> randomQuestions = new ArrayList<Question>(NUMBER_OF_QUESTIONS);
for (int i = 0; i < NUMBER_OF_QUESTIONS; i++) {
int randomQuestionElementsCapacity = getRandomQuestionElementsCapacity();
Question question = new Question(randomQuestionElementsCapacity);
for (int j = 0; j < randomQuestionElementsCapacity; j++) {
boolean isLastIteration = j + 1 == randomQuestionElementsCapacity;
QuestionElement questionElement = new QuestionElement();
questionElement.setValue(getRandomQuestionElementValue());
questionElement.setOperator(isLastIteration ? null
: Operator.values()[randomGenerator.nextInt(Operator.values().length)]);
question.addElement(questionElement);
}
randomQuestions.add(question);
}
return randomQuestions;
}
private int getRandomQuestionElementsCapacity() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENTS, MAX_QUESTION_ELEMENTS);
}
private int getRandomQuestionElementValue() {
return getRandomIntegerFromRange(MIN_QUESTION_ELEMENT_VALUE, MAX_QUESTION_ELEMENT_VALUE);
}
private int getRandomIntegerFromRange(int min, int max) {
return randomGenerator.nextInt(max - min + 1) + min;
}
}
class Question {
private List<QuestionElement> questionElements;
public Question(int sizeOfQuestionElemets) {
questionElements = new ArrayList<QuestionElement>(sizeOfQuestionElemets);
}
public void addElement(QuestionElement questionElement) {
questionElements.add(questionElement);
}
public List<QuestionElement> getElements() {
return questionElements;
}
public int size() {
return questionElements.size();
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (QuestionElement questionElement : questionElements) {
sb.append(questionElement);
}
return sb.toString().trim();
}
}
class QuestionElement {
private int value;
private Operator operator;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
#Override
public String toString() {
return value + (operator == null ? "" : " " + operator.getDisplayValue()) + " ";
}
}
enum Operator {
PLUS("+"), MINUS("-"), MULTIPLIER("*"), DIVIDER("/");
private String displayValue;
private Operator(String displayValue) {
this.displayValue = displayValue;
}
public String getDisplayValue() {
return displayValue;
}
}
Run and preview. Hope this helps.
Thanks to:
Generating random number in
range
Retrieving random
element from array
Create an array char[] ops = { '+', '-', '/', '*' } and create a random int i in range [0,3], and chose ops[i]
You will need to take care that you do not generate a divide by zero question.
You can make it even more generic by creating an interface MathOp and creating 4 classes that implement it: Divide, Sum , ... and create an array: MathOp[] ops instead of the char[]
Using this, it will also give you much easier time to check the result later on...
Put your operators in an array (4 elements), generate a random integer from 0 to 3, and pick the operator that is at this index in the array.
Do that each time you need to have a random operator, i.e. after every number of your question except the last one.
Make an array that has one entry for each of the operators. Then generate a random number between 0 and the length of the array minus 1.
So since each operation is binary you can just worry about figuring out the base case and then building up your expressions from there.
An easy way would just to select a random number an correlate that which operation will be used.
int displayAnswer(int leftSide, int rightSide, int operation {
int answer;
string operation;
switch(operation) {
case 1:
operation = "+";
answer = leftSide + rightSide;
break;
case 2:
operation = "-";
answer = leftSide - rightSide;
break;
case 3:
operation = "*";
answer = leftSide * rightSide;
break;
case 4:
operation = "/";
answer = leftSide / rightSide:
break;
}
textView.setText(leftSide + operation + rightSide);
return answer;
}

Categories