How can I test a class that returns the Fibonacci series?
I used an iterator for this code.
The FibonacciIteratorTest class is below.
public class FibonacciIterator implements Iterator<Integer>, Iterable<Integer>{
private int num1;
private int num2;
private int num3;
private int count;
private int to;
public FibonacciIterator(int to){
this.num1 = 0;
this.num2 = 1;
this.to = to;
this.count = -1;
}
public static Iterable<Integer> to(int num){
return new FibonacciIterator(num);
}
#Override
public Iterator<Integer> iterator(){
return this;
}
#Override
public boolean hasNext(){
if(count < to){
count++;
return true;
}
return false;
}
#Override
public Integer next(){
if(count < 2){
return count;
}
num3 = num1 + num2;
num1=num2;
num2=num3;
return num3;
}
}
Instead of 55, the expected values should be 0 1 1 2 3 5 8 13 21 34 55.
class FibonacciIteratorTest {
#Test
void shouldReturnFibonacciNumbers(){
FibonacciIterator fibonacciNumbers= new FibonacciIterator();
assertEquals(55,fibonacciNumbers.to());
}
}
Considering your fibonacciNumbers.to method returning int [] then you might want to use assertArrayEquals:
int arr[]={0,1,1,2,3,5,8,13,21,34};
assertArrayEquals(arr, fibonacciNumbers.to(10));
If your method fibonacciNumbers.to() returns other than int array, then please tell us, so that answer can be changed accordingly.
Assuming your FibonacciIterator.to(int) method returns an Iterator<Integer>:
#Test
void shouldReturnFibonacciNumbers(){
var groundTruth = new ArrayList(Arrays.asList(1,1,2,3,5,8,13,21,34,55)).iterator();
var fibonacciNumbers = new FibonacciIterator().to(10);
while(groundTruth.hasNext()){
if(!fibonacciNumbers.hasNext()){
fail("Length doesn't match");
}
assertEquals(groundTruth.next(), fibonacciNumbers.next());
}
}
I didn't test the code, but it should at least be close to working.
Related
I have a Result class in which I keep all values/results.
All my code:
public class Main {
public static void main(String[] args) {
Main main = new Main();
Result result = new Result();
Divider divider = new Divider();
String[] myTestArray = new String[]{"1234", "12"};
if (myTestArray.length != 2) {
System.out.printf("You can not use %d arguments. " +
"To perform division, you need to use 2 arguments `", myTestArray.length);`
System.exit(1);
}
int dividend = Integer.parseInt(myTestArray[0]);
int divisor = Integer.parseInt(myTestArray[1]);
divider.divide(dividend, divisor);
Formatter formatter = new Formatter();
formatter.format(result);
}
}
public class Divider {
Result result;
public Divider() {
this.result = new Result();
}
/**
* divide method performs division of two numbers
*/
public void divide(int dividend, int divisor) {
result.setDividend(Math.abs(dividend));
result.setDivisor(Math.abs(divisor));
result.setQuotient(divideTwoNumbers(result.getDividend(),
result.getDivisor()));
}
/**
*
*/
public int calculateProduct(int partialDividend) {
int multiplicand = divideTwoNumbers(partialDividend, `result.getDivisor());`
result.setProduct(multipleTwoNumbers(result.getDivisor(), `multiplicand));`
result.setRemainder(partialDividend - result.getProduct());
return result.getProduct();
}
/**
* Method divideTwoNumbers is used instead of operands "/"
*/
public int divideTwoNumbers(int dividend, int divisor) {
int result = 0;
for (int i = 0; dividend >= divisor; i++) {
dividend = dividend - divisor;
result++;
}
return result;
}
/**
* Method multipleTwoNumbers is used instead of operands "*"
*/
public int multipleTwoNumbers(int multiplicand, int multiplier) {
int product = 0;
for (int i = 0; i < multiplicand; i++) {
product = product + multiplier;
}
return product;
}
}
I think, my problem is around here somewhere
public class Formatter {
Result result;
Divider divider;
private int firstIndexPartialDividend = 0; // find the beginning of the number
private int countSpace = 0; // space counter
public Formatter() {
this.result = new Result();
this.divider = new Divider();
}
public void format() {
// print the first row
printFirstRow();
String dividendText = Integer.toString(result.getDividend());
for (int i = 1; i <= dividendText.length(); i++) {
result.setFirstPartialDividend(Integer.parseInt
(dividendText.substring(firstIndexPartialDividend, i)));
// print the second row
if (result.getFirstPartialDividend() >= result.getDivisor() &&
firstIndexPartialDividend == 0) {
countSpace = dividendText.length() - i;
printSecondRow(result.getFirstPartialDividend());
firstIndexPartialDividend = i;
// To align the space in the next row.
if (Integer.toString(result.getProduct()).length()
> Integer.toString(result.getRemainder()).length() &&
result.getRemainder() > 0) {
countSpace = Integer.toString(result.getProduct()).length()
- Integer.toString(result.getRemainder()).length();
} else {
countSpace = 0;
}
}
}
}
/**
* printFirstRow method - print the first row of an application
*/
public void printFirstRow() {
System.out.printf("%d|%d\n", result.getDividend(), `enter code here`result.getDivisor());
}
/**
* printSecondRow method - print the second row of an application
*/
public void printSecondRow(int firstPartialDividend) {
divider.calculateProduct(firstPartialDividend);
System.out.println(result.getProduct() + getSpace(countSpace) + `enter code here`"|" + (result.getQuotient()));
}
/**
* getSpace method to get the number of spaces you want
*/
public String getSpace(int count) {
String space = "";
for (int i = 0; i < count; i++)
space += " ";
return space;
}
}
public class Result {
private int quotient; // keep the result of division
private int dividend;
private int divisor;
private int firstPartialDividend; //keep the result of division the `enter code here`first partial dividend
private int product;
private int remainder;
`enter code here`public Result() {
this.dividend = dividend;
this.divisor = divisor;
}
public int getQuotient() {
return quotient;
}
public void setQuotient(int quotient) {
this.quotient = quotient;
}
public int getDividend() {
return dividend;
}
public void setDividend(int dividend) {
this.dividend = dividend;
}
public int getDivisor() {
return divisor;
}
public void setDivisor(int divisor) {
this.divisor = divisor;
}
public int getFirstPartialDividend() {
return firstPartialDividend;
}
public void setFirstPartialDividend(int firstPartialDividend) {
this.firstPartialDividend = firstPartialDividend;
}
public int getProduct() {
return product;
}
public void setProduct(int product) {
this.product = product;
}
public int getRemainder() {
return remainder;
}
public void setRemainder(int remainder) {
this.remainder = remainder;
}
}
values are still 0
My program should print long division result
Like this:
1234|12
12 |102
34
24
10
Of course this is not the whole program, I am still working on it.
The image shown has stopped before the assignment is complete. The parameter value is 1234, and the current value of this.dividend is zero. If you step the debugger forward, both will have the value of 1234
Your setters are working fine. You are just not calling the setters on the correct instances.
Regarding the "issue". You have a Result and Divider instance in main method that is not given to the Formatter. When you create a new Formatter() it has its own instances that are initialized with the default values of zero.
You probably should have a constructors that carry through the same instances. For example
Result result = new Result(); // this probably isn't even needed
Divider divider = new Divider(result); // param could be removed
divider.divide(x1, x2); // This method could create and store `new Result()` value on its own
Formatter formatter = new Formatter(divider, result); // again, result not needed since it would be internal to the divider
formatter.format();
(and your formatter should probably only "format the result" as the name implies instead of also doing calculations with the Divider instance)
You can also remove new Main() since that isn't doing anything
OneCricketeer - thanks a lot!!!
I has changed constructor Divider and Formatter.
Result result = new Result();
Divider divider = new Divider(result);
divider.divide(dividend, divisor);
Formatter formatter = new Formatter(result);
formatter.format();
public Divider(Result result) {
this.result = result;
}
public Formatter(Result result) {
this.result = result;
this.divider = new Divider(result);
}
Now my output is
1234|12
12 |102
I have a dice class that rolls random numbers from 1-6. I want to create another class that implements checking of all numbers and stops rolling when all unique numbers are rolled once. Not sure how I would use the getFace and boolean method. Thinking of every number starting at false and outcomes true once number appears.
public class Die {
public final int MAX = 6; //max 6
private int faceValue; //current value showing on die
//constructor
public Die() {
faceValue = 1;
}
public int roll(){
faceValue = (int)(Math.random()*MAX)+1;
return faceValue;
}
public void setFaceValue(int value){
if(value> 0 && value <=MAX)
faceValue=value;
}
public int getFaceValue(){
return faceValue;
}
public String toString(){
String result = Integer.toString(faceValue);
return result;
}
}
ArrayList<Integer> numList = new ArrayList<Integer>();
//Add 1-6
for(int i = 1;i < 7;i++){
numList.Add(i);
}
Die dice = new Die();
While(numList.size() != 0){
int rolled = dice.roll();
ArrayList.remove(rolled);
}
I assume the code goes something like that. Haven't touch java for a bit.
Logic:
Create a set S. Keep rolling and adding the outcome to that set. Stop when the size of the set is 6. (Set contains unique elements only.)
import java.util.HashSet;
import java.util.Set;
public class Play {
public static void main(String[] args) {
Die die = new Die();
Set<Integer> set = new HashSet<>();
int outcome = 0;
//Keep rolling until set size is 6.
while(set.size() != 6) {
outcome = die.roll();
set.add(outcome);
}
System.out.println(set);
}
}
class Die {
public final int MAX = 6; //max 6
private int faceValue; //current value showing on die
//constructor
public Die() {
faceValue = 1;
}
public int roll(){
faceValue = (int)(Math.random()*MAX)+1;
return faceValue;
}
public void setFaceValue(int value){
if(value> 0 && value <=MAX)
faceValue=value;
}
public int getFaceValue(){
return faceValue;
}
public String toString(){
String result = Integer.toString(faceValue);
return result;
}
}
I've got 2 integer values, e.g. a = 10 and b = 20.
Now i want to substract them: a - b, but as a result i don't want to have negative values, so in this example i want the result 0 and a new integer variable with the rest (10 here).
Two more examples:
Input: a=40, b=20; Expected Output:20
input: a=25 b=50 Expected Output: 0 and a new int var = 25
How to do this in java without external libraries?
From what I understand, you want a variable to be holding the result if the result is greater than or equal to 0. Otherwise, that variable should hold 0 and another variable will hold a positive value of the result.
If this is the case, consider the following code snippet:
int result = a -b;
int otherVariable = 0;
if (result < 0) {
otherVariable = -result;
result = 0;
}
int aMinusB = a-b;
int output = Math.max(aMinusB,0);
int rest = aMinusB < 0 ? Math.abs(aMinusB) : 0;
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
There are two ways to solve this problem: -
First: -
If you don't want to create a method to return this value and only to display it, then you can do it by printing out the results of if-else block in the code below within the function itself.
Second: -
If you want to use the result somewhere else, go for an object based approach: -
// Main class
public class SubtractWithRest {
public static void main(String[] args) {
SubtractResultWithRest subtractResultWithRest = new SubtractResultWithRest();
subtraction(10, 20, subtractResultWithRest);
System.out.println("Result: " + subtractResultWithRest.getResult());
System.out.println("Rest: " + subtractResultWithRest.getRest());
}
private static void subtraction(int num1, int num2, SubtractResultWithRest subtractResultWithRest) {
if (num2 > num1) {
subtractResultWithRest.setResult(0);
subtractResultWithRest.setRest(num2 - num1);
} else {
subtractResultWithRest.setResult(num1 - num2);
}
}
}
// Object class
public class SubtractResultWithRest {
private int result;
private int rest = 0;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public int getRest() {
return rest;
}
public void setRest(int rest) {
this.rest = rest;
}
}
UPDATE: I've tried changing the return type on the getCalcMean() and calcMean() methods to double to make it more accurate, and everything inside the Person class works fine, but Inside the program class it's now saying "Incompatible Types: possible lossy conversion from double to int." at System.out.println(math1.calcMean(math1.getCalcMean())); I understand what the error means but I'm not sure how to fix it as the final result needs to be double and I thought java could calculate a double and int and get a double. What am I doing wrong?
<<>>
I'm trying to calculate the mean of the total after 999 is typed, but it keeps showing 0, and I can't see why.
Can someone tell me how to get my getCalcMean() method to show the mean as numTotal/count?
--- Class Program ---
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int count = 1;
Math math1 = new Math(num, count);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
count ++;
System.out.println("Total till now:" + math1.getNumTotal());
}
}
math1.setCount(count);
System.out.println(math1.getNumTotal());
System.out.println(math1.calcMean(math1.getCalcMean()));
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
---- Class Math ----
public class Math {
private int num;
private int numTotal;
private double mean;
private int count;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int count) {
this.num = num;
this.count = count;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public double getCalcMean(){
return this.mean;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(double value){
this.mean = value;
}
public void setCount(int value){
this.count = value;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public double calcMean(int num){
this.numTotal = numTotal;
mean = numTotal / this.count;
return mean;
}
}
counter ++ in your code is meaningless since you never pass it to Math object.
math1.getCalcMean() will return the mean in Math object but mean hasn't been calculated yet.
Advice:
Add getter and setter for counter in Math class.
Calculate the mean in getCalcMean() method.
Plese see the code below. I assume that you use 999 as the end flag so haven't took it into account. The counter is initialized with 0.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int counter = 0;
Math math1 = new Math(num, counter);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
counter ++;
math1.setCounter(counter);
System.out.println("Total till now:" + math1.getNumTotal());
}
}
System.out.println(math1.getNumTotal());
System.out.println(math1.getCalcMean());
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
And also the Math class.
public class Math {
private int num;
private int numTotal;
private int mean;
private int counter;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int counter) {
this.num = num;
this.counter = counter;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public int getCalcMean(){
mean = numTotal / this.counter;
return mean;
}
public int getCounter(){
return this.counter;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(int value){
this.mean = value;
}
public void setCounter(int counter){
this.counter = counter;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public void calcMean(int num){
mean = numTotal / this.counter;
}
}
I'm trying to add elements to an array. The elements of the array are of a custom class called variable. In the problematic for loop, it basically adds the last element trying to be added throughout the loop. Any help would be appreciated!
import java.util.*;
public class ThiefsDilemma2{
public static void main(String[] args){
ArrayList values = new ArrayList(args.length/2);
Valuable[] array = new Valuable[args.length/2];
if(args.length%2 ==1){
int weight = Integer.parseInt(args[args.length-1]);
boolean room = true;
int tracker = 0;
//problem!!!! Adds the last element throughout the loop
for(int i = 0; i < args.length/2; i++){
array[i] = new Valuable(
Integer.parseInt(args[args.length/2+i]),
Integer.parseInt(args[i]));
}
for(int i = 0; i < args.length/2; i++){
System.out.println(array[i]);
}
while(values.size() > 0 && room){
int lightest = 100000;
double value = 0.0;
int index = 0;
int counter = 0;
for(Object p: values){
Valuable test = (Valuable)p;
//System.out.println(test);
if(test.getWeight() < lightest && !test.beenUsed()){
lightest = test.getWeight();
//System.out.println(lightest);
}
if(test.getValue() > value && !test.beenUsed()){
index = counter;
value = test.getValue();
//System.out.println(value);
}
else if(test.getValue() == value || !test.beenUsed()){
if(test.getWeight() <= test.getWeight()){
index = counter;
}
}
counter++;
}
//System.out.println(counter + " " + lightest + " " + value);
Valuable p = ((Valuable)(values.get(index)));
p.used();
if(lightest > weight){ room = false;}
else{
if(p.getWeight() <= weight){
weight -= p.getWeight();
}
System.out.println(p);
values.remove(p);
}
}
}
}
public static class Valuable{
private static double value;
private static int weight;
private static boolean used = false;
public Valuable(int top, int bottum){
value = ((double)top/(double)bottum);
weight = bottum;
//System.out.println(weight + " " + value);
}
public static double getValue(){
return value;
}
public static int getWeight(){
return weight;
}
public String toString(){
return value + " " + weight;
}
public static void used(){
used = true;
}
public static boolean beenUsed(){
return used;
}
}
}
The problem is that all data members of Valuable are static. This means that they are shared by all instances of the class:
private static double value;
private static int weight;
private static boolean used = false;
Remove the static qualifiers from the data members, and from the getter functions.