Create a simple math game using java objects - java

I am trying to create a Simple math game using Java objects. My goal is to create a question class, which contains a method to show a question with random numbers, a method to check the answer, a question constructure.
How can I generate 10 random questions using these objects? With additions, substraction and multiplication questions. And print the how many correct answers, at the end.
I have created my question class and my first method shows a random question using the variables "a" and "b". and store the answer.
My second method check the answer with the user input and print the result. So far when I run my program it only shows the same question over and over again.
This is my Question class
import java.util.*;
public class Question {
private int a;
private int b;
private String Question;
private int correct;
Random rand = new Random();
Scanner input = new Scanner(System.in);
int count = 0;
Question(int c, int d) {
x = rand.nextInt(20);
y = rand.nextInt(20);
}
public void askQuestion() {
if (a > b) {
System.out.println("What is " + a + " - " + b + " ?\n");
correct = a - b;
} else {
System.out.println("What is " + a + " + " + b + " ?\n");
correct = a + b;
}
}
public void Check() {
int response = Integer.parseInt(input.next());
if (response == correct) {
System.out.printf("yes.\n");
count++;
} else {
System.out.printf("No. It is " + correct + ".\n");
}
}
}
my main method looks like this
public class Main {
public static void main(String[] args) {
Question q1 = new Question(1,2);
for (int i = 1; i < 10; i++) {
q1.askQuestion();
q1.check();
}
}
}
In my output it shows the question with two random numbers but it prints the same question over and over again. EX:
What is 13 - 1 ?
12
That is correct.
What is 13 - 1 ?
12
That is correct.
What is 13 - 1 ?
3
Wrong!. The answer is 12.
What is 13 - 1 ?
Eventually I want my output to look like:
What is 4 + 6?
What is 7 - 3?
Any help to fix this? and make this game more interactive? Appreciate it.

Your problem is due to the fact that you are creating one Question object, that generates two random numbers (13 and 1 in your case). You then go through a loop of asking 10 Questions, but you use the same Question object - so you are using the same random numbers every time. To fix this, do the following changes:
In your Question constructor, get rid of the parameters, you do not need them. Assign to variables a and b:
private Question(){
a = rand.nextInt(20);
b = rand.nextInt(20);
}
So every time you create a Question, you will generate two random numbers which you assign to your variables you declared earlier in the code at the top (in your code, a and b are declared, but not used).
Then in your main, change it to the following:
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
Question q1 = new Question();
q1.askQuestion();
q1.check();
}
System.out.println("Number correct: " + count); //print amount correct, to use this make variable "count" static.
}
The changes are that now you are creating a new Question object every time you go through the loop, and get new random values. Every time it asks a new Question, it will create a new Question object with new random values and overwrite the old ones. It will ask the question 10 times after you give and check the answer, after which the program will output number of correct answers and stop.
Example output for 3 questions:
What is 17 - 15 ?
2
yes.
What is 8 + 11 ?
19
yes.
What is 9 - 0 ?
5
No. It is 9.
Number correct: 2

If you want a way to dynamically ask a question with random numbers and operators, you can create an Operator enum as seen below to handle calculating the result of a left-hand and right-hand value.
Also, the calls to System.out.print should be in the main program as much as possible. Instead, you should return strings from the Question.
All you need to do is pass the two randomly-generated numbers to the Operator enum and ask it to calculate the result.
Exam (main)
package exam;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Exam {
private static int correctCount = 0;
private static List<Question> questions = randomQuestions(10);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
questions.stream().forEach(question -> ask(question, input));
input.close();
stats();
}
private static void ask(Question question, Scanner input) {
System.out.print(question.askQuestion());
double guess = input.nextDouble();
boolean isCorrect = question.makeGuess(guess);
System.out.println(question.explain(isCorrect));
System.out.println();
correctCount += isCorrect ? 1 : 0;
}
private static void stats() {
double percentage = (correctCount * 1.0d) / questions.size() * 100;
System.out.printf("Correct: %.2f%% (%d/%d)%n", percentage, correctCount, questions.size());
}
private static List<Question> randomQuestions(int count) {
List<Question> questions = new ArrayList<Question>();
while (count --> 0) questions.add(new Question());
return questions;
}
}
Question (class)
package exam;
import java.util.Random;
public class Question {
private static final Random RAND = new Random(System.currentTimeMillis());
private double left;
private double right;
private Operator operator;
public Question(double left, double right, Operator operator) {
this.left = left;
this.right = right;
this.operator = operator;
}
public Question(int max) {
this(randInt(max), randInt(max), Operator.randomOperator());
}
public Question() {
this(10); // Random 0 -> 10
}
public String askQuestion() {
return String.format("What is %s? ", operator.expression(left, right));
}
public String explain(boolean correct) {
return correct ? "Correct" : String.format("Incorrect, it is: %.2f", calculate());
}
public boolean makeGuess(double guess) {
return compareDouble(guess, calculate(), 0.01);
}
private double calculate() {
return operator.calculate(left, right);
}
#Override
public String toString() {
return String.format("%s = %.2f", operator.expression(left, right), calculate());
}
private static boolean compareDouble(double expected, double actual, double threshold) {
return Math.abs(expected - actual) < threshold;
}
private static double randInt(int range) {
return Math.floor(RAND.nextDouble() * range);
}
}
Operator (enum)
package exam;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public enum Operator {
ADD("+", (left, right) -> left + right),
SUB("-", (left, right) -> left - right),
MUL("*", (left, right) -> left * right),
DIV("/", (left, right) -> left / right);
private static final Random RAND = new Random(System.currentTimeMillis());
private static final List<Operator> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
public static Operator randomOperator() {
return VALUES.get(RAND.nextInt(SIZE));
}
private String symbol;
private Operation operation;
private Operator(String symbol, Operation operation) {
this.symbol = symbol;
this.operation = operation;
}
public double calculate(double left, double right) {
return operation.calculate(left, right);
}
public String expression(double left, double right) {
return String.format("%.2f %s %.2f", left, symbol, right);
}
#Override
public String toString() {
return symbol;
}
}
Operation (interface)
package exam;
public interface Operation {
double calculate(double left, double right);
}

Related

How do i compare the values of objects in an object array?

My code outputs this:
Computer 1 bets 5
Computer 2 bets 8
Computer 3 bets 4
Computer 4 bets 3
Computer 5 bets 8
I want to make a method "displayWinners()" that compares the bet value of all the objects in this array and returns all of the object id's with the highest bet value, in this case it would be Computer 2 and 5 with a bet of 8. How would i do that?
public class Computer {
Computer[] c;
private int id;
private int bet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.println();
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
why don't you allocate a variable for an index of the maximum value and a value itself, and keep checking & rewriting the variable as function bet() is executed.
the code below is not properly verified but just have a look over.
public class Computer {
Computer[] c;
private int id;
private int bet;
private List<Integer> maxId;
private int maxBet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
maxId = new ArrayList<Integer>();
maxBet = 0;
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
if(c[i].bet > maxBet) {
maxId = new ArrayList<Integer>();
maxId.add(c[i].id);
maxBet = c[i].bet;
}
else if(c[i].bet == maxBet) {
maxId.add(c[i].id);
}
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.format("Computer %d", maxId.get(0));
if(maxId.size() > 1) {
for(int i=1; i<maxId.size(); i++) {
System.out.format(" and %d", maxId.get(i));
}
}
System.out.format(" with a bet of %d\n", maxBet);
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
Ok, just for the fun to provide this with a small trick.
You just iterate your array.
Then, I will compare the current bet with the maximum value known using Integer.compare and base on the result, I will either:
r > 0 - clear the list and add the instance to the list
r == 0 - Add the instance to the list
r < 0 - Do nothing
Good to know, the actual value return by the method are simpler [-1, 0, 1], it will matter shortly.
Now, we can see some redondance in adding into the list, to reduce that, we are able to use a switch instead of ifs.
List<Computer> winners = new ArrayList<Computer>();
for ( Computer c : computers ){
int r = Integer.compare(c.getBet(), maxBet);
switch(r){
case 1: //Current bet is higher
maxIds.clear();
maxBet = c.getBet();
case 0: //Current bet is equals
winners.add(c);
case -1: //Current bet is lower (optional line, just for the explanation)
}
}
Since I don't use break, after we clear the list, we will add into it.
Note: A fail-safe should be added in case of Integer.compare implementation changes. The documentation state that it will return any value instead of -1, 0 or 1. But the current implementation is simpler :
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
First of all, I recommend you to split storage and business logic. Move all methods for show Computer class out.
So to find the winners you have to do following steps:
Create a list of computers (you can create an array or a list);
Iterate over the collection once to find the highest bet;
Iterate over the collection second time to filter out all computers with the highest bet.
If you ask such question, then I suppose, that no need of you right now to offer different sorting algorithms or special data structures (they all do the same, but much faster for big input data).
This is one of the possible solutions (I tried to keep it simple):
public class Foo {
public static void main(String[] args) throws IOException {
Computer[] computers = createComputer(5);
int highestBet = getHighestBet(computers);
List<Integer> ids = getIdsWithBet(computers, highestBet);
System.out.println(ids.stream().map(String::valueOf).collect(Collectors.joining(",")));
}
private static int getHighestBet(Computer... computers) {
int max = 0;
for (Computer computer : computers)
max = Math.max(max, computer.getBet());
return max;
}
private static List<Integer> getIdsWithBet(Computer[] computers, int bet) {
List<Integer> ids = new ArrayList<>(computers.length);
for (Computer computer : computers)
if (computer.getBet() == bet)
ids.add(computer.getId());
return ids;
}
// you van use List<Computer>
private static Computer[] createComputer(int total) {
Random random = new Random();
Computer[] computers = new Computer[total];
for (int i = 0; i < computers.length; i++) {
computers[i] = new Computer(i + 1, random.nextInt(10) + 1);
System.out.println(computers[i]);
}
return computers;
}
}
// It's better to use unmodifiable objects if you can
final class Computer {
private final int id;
private final int bet;
public Computer(int id, int bet) {
this.id = id;
this.bet = bet;
}
public int getId() {
return id;
}
public int getBet() {
return bet;
}
#Override
public String toString() {
return "Computer " + id + " bets " + bet;
}
}
import java.util.ArrayList at top of file
```
int maxBet = 0;
ArrayList<Integer> maxIds = new ArrayList<Integer>();
// This is a for each loop, it is saying, for each computer in the list of computers
for ( Computer computer : computers ){
/* if that computer has a higher bet than what we previously thought
was the highest, empty our list and set maxBet to that, and add this
computer to the list of computers that have that bet number */
if (computer.getBet() > maxBet){
maxIds.clear();
maxBet = computer.getBet();
maxIds.add(computer.getId());
// another computer has the same max bet value
} else if ( computer.getBet() == maxBet){
maxIds.add(computer.getId());
}
}
System.out.println("Max Bet: " + maxBet);
System.out.print("Computers with max bet: ");
// for each id in our list of computers that have the max bet
for ( int id : maxIds ){
System.out.print(id + " ");
}

Return the result of each iteration in the loop

I'm doing something that produces the right result. However, it is wrong from a design POV.
The point of the program is to list the result of all the powers of a number up to and including the user-defined limit.
I have a constructor which accepts the base and the exponent from the Scanner. Then a method, which utilises a for loop to calculate the power for each exponent.
Now, the problem is that I'm printing the result from each loop iteration directly from this method. This beats the point of private variables and it being void in the 1st place.
Therefore, I want to define a getter method which returns the result of each power to the output. I used to set them just fine for if/switch statements, but I don't know how to do the same for loops. If I assign the result to a variable within the loop and return that variable from the getter then it will return only the output from the final iteration.
Private implementation
package Chapter6Review;
public class Powers {
private int target;
private int power;
public Powers(int target, int power) {
this.target = target;
this.power = power;
}
public void calculatePower() {
for (int i = 0; i <= power; i++) {
System.out.println((int) Math.pow(target, i));
}
}
/*
public int getPower() {
return
}
*/
}
User interface
package Chapter6Review;
import java.util.Scanner;
public class PowersTester {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your base: ");
int target = in.nextInt();
System.out.print("Enter your exponent: ");
int power = in.nextInt();
Powers tester = new Powers(target, power);
tester.calculatePower();
}
}
You can simply use a List ;
public List<Integer> calculatePower() {
int p;
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i <= power; i++) {
p = (int) Math.pow(target, i);
result.add(p);
}
return result;
}
Then in you main method, you can iterate the list to print the powers like that :
List<Integer> result = new ArrayList<Integer>();
Powers tester = new Powers(target, power);
result = tester.calculatePower();
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
You could store each of the results in a List:
List<Power> list = new ArrayList<>();
and when you call it add it as well
list.add(new Powers(target, power));
At the end you can iterate over the list like this:
for (Power power : list){
// your code
}
You might consider using streams as well
public List<Integer> calculatePower() {
return IntStream
.rangeClosed(0, power). // iterate from 0 till power inclusive
.mapToObj(i -> (int) Math.pow(target,i))
.collect(Collectors.toList()); // get result as list
}
Thanks for all the answers. Using a list seems to be a good choice.
Since I haven't covered lists yet, I resorted to this solution for now. But I don't like having code that can affect the solution in the main. Ideally, the loop should go in the private implementation.
Main
Powers tester = new Powers(target, power);
for (int i = 0; i <= power; i++) {
tester.calculatePower(i);
System.out.println(tester.getPower());
}
Private implementation
public void calculatePower(int iPower) {
result = (int) Math.pow(target, iPower);
}
public int getPower() {
return result;
}

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.

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;
}

How to turn static methods into non-static. Small explanation/examples related to java oop

I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.

Categories