我制作了这段代码来计算数字:
import java.util.Random;
public class Sorting {
private double[] player;
private int k=5;
private int j=5;
public void sort(){
player = new double[k];
for(int i=1;i<k;i++){
double tempp ;
for(i=1;i<j;i++){
tempp = Math.random() * i;
player[i]=tempp;
System.out.println("Result "+i+"="+player[i]);
}
}
}
public static void main(String []args){
Sorting k=new Sorting();
k.sort();
}}
结果是:
Result 1=0.4529689730194949
Result 2=0.09643822768644617
Result 3=1.841047494651026
Result 4=2.1807153629323777
现在,我想添加一个标签,从最大到最小的结果编号标记为EXCELLENT,VERY GOOD,GOOD和BAD,如下所示:
Result 1=0.4529689730194949 labeled GOOD
Result 2=0.09643822768644617 labeled BAD
Result 3=1.841047494651026 labeled VERY GOOD
Result 4=2.1807153629323777 labeled EXCELLENT
答案 0 :(得分:0)
public class Sorting
{
private double[] player;
private int k=5;
private int j=5;
String[] rating = {"BAD", "GOOD", "VERY GOOD", "EXCELENT"};
public void sort()
{
player = new double[k];
for(int i=1; i<k; i++)
{
double tempp;
for(i=1; i<j; i++) // i should probably be zero since your array starts on value 0, not 1.
{
tempp = Math.random() * i;
player[i]=tempp;
System.out.println("Result " + i + " = " + player[i] + " Rating is " + rating[(int)player[i]]);
}
}
}
public static void main(String[] args)
{
Sorting k = new Sorting();
k.sort();
}
}
你的代码似乎有些奇怪,但我解决了你所问的问题。
答案 1 :(得分:0)
TreeSet已默认对数字进行排序。
这是我的版本:
示例输出:
结果:0.12754837127918317 =&gt; BAD
结果:0.7956890627771006 =&gt;优秀
结果:0.3123868511945034 =&gt; GOOD
结果:0.6332109887264882 =&gt; VERY_GOOD
public class FourRandomNumbersEvaluator {
private TreeSet<Double> numbers;
private Map<Double,Evaluation> numbersWithEvaluations = new HashMap<Double,Evaluation>();
private enum Evaluation {BAD, GOOD, VERY_GOOD, EXCELLENT}
private static final int NUMBER_OF_GENERATED_NUMBERS = 4;
public FourRandomNumbersEvaluator(TreeSet<Double> numbers) {
if(numbers == null || numbers.size() != 4){
throw new IllegalArgumentException("your have to provide exactly 4 numbers");
}
this.numbers = numbers;
}
public static void main(String[] args) {
FourRandomNumbersEvaluator evaluator = new FourRandomNumbersEvaluator(generateNumbers());
evaluator.evaluate();
evaluator.printNumbersWithEvaluations();
}
private static TreeSet<Double> generateNumbers() {
TreeSet<Double> numbers = new TreeSet<Double>();
while(numbers.size() < NUMBER_OF_GENERATED_NUMBERS){
double number = Math.random();
if(numberNotAlreadyExisting(numbers, number)){
numbers.add(number);
}
}
return numbers;
}
private static boolean numberNotAlreadyExisting(TreeSet<Double> numbers, double number) {
return !numbers.contains(number);
}
public void evaluate() {
int i = 0;
for(Double number : numbers){
numbersWithEvaluations.put(number, Evaluation.values()[i++]);
}
}
private void printNumbersWithEvaluations(){
for(Map.Entry<Double,Evaluation> numberWithEvaluation : numbersWithEvaluations.entrySet())
System.out.println("Result: "+ numberWithEvaluation.getKey() + " => " + numberWithEvaluation.getValue());
}
}