Skip to content

Commit

Permalink
The answers with decimals now always show two decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
UO289845 committed Apr 26, 2024
1 parent 7e2caaf commit 8e70c74
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import main.java.questionGenerator.question.answers.formatAnswers.AddUnitsFormater;
import main.java.questionGenerator.question.answers.formatAnswers.EmbellishNumbersFormater;
import main.java.questionGenerator.question.answers.formatAnswers.RemoveEFromNumber;
import main.java.questionGenerator.question.answers.formatAnswers.SetAmountOfDecimals;

public class SizeGenerator extends AnswersAreNotEntites {

Expand Down Expand Up @@ -45,7 +46,7 @@ private String getRightAnswerEntity(String url) {
@Override
public List<String> decorateAnswers(List<String> answers) {
AnswerFormater formater = new RemoveEFromNumber(new EmbellishNumbersFormater(
new AddUnitsFormater(null, "km^2")));
new SetAmountOfDecimals(new AddUnitsFormater(null, "km^2"), 2)));
return formater.format(answers);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main.java.questionGenerator.question.answers.formatAnswers;

import java.util.ArrayList;
import java.util.List;

import main.java.questionGenerator.question.answers.AbstractFormater;
import main.java.questionGenerator.question.answers.AnswerFormater;

public class SetAmountOfDecimals extends AbstractFormater {

private int amount;

public SetAmountOfDecimals(AnswerFormater formater, int amount) {
super(formater);
this.amount = amount;
}

@Override
public List<String> format(List<String> answers) {
List<String> result = new ArrayList<>();
for(String answer : answers) {
String[] splitted = split(answer);
if(splitted.length==0)
result.add(answer);
else {
String decimalPart = formatDecimalPart(splitted[1]);
result.add(splitted[0] + '.' + decimalPart);
}
}
return end(result);
}

private String[] split(String answer) {
String[] result = {"", ""};
int position = 0;
for(char c : answer.toCharArray()) {
if(c=='.')
position = 1;
else
result[position] += c;
}
return result;
}

private String formatDecimalPart(String decimalPart) {
if(decimalPart.length()<amount) {
int diference = amount - decimalPart.length();
for(int i=0; i<diference; i++) {
decimalPart += "0";
}
}
else if(decimalPart.length()>amount) {
char[] aux = decimalPart.toCharArray();
decimalPart = "";
for(int i=0; i<amount; i++) {
decimalPart += aux[i];
}
}
return decimalPart;
}

}

0 comments on commit 8e70c74

Please sign in to comment.