仅作为序言,我对Java编码很新,或者编码一般都是准确的。
这是我想要完成的。这是一个项目,我们在其中输入一个数字的输入文件,一个整数是竞争者的数字,下一个是他们捕获的鱼的重量(看起来像这个3 26.7(每两个数字的新行)2 2.6 ..所以等等),将它们放在一个数组中,然后以某种方式对它们进行排序。现在,我将发布整个代码,但这只是最后一种方法,“排序”,我现在遇到了困难。
该方法是一种气泡分选方法。我接近它的方式是,它将采用第一个数组,将其与第二个数组进行比较以查看它是否小于,然后交换两个竞争者数字,如果逻辑是正确的,以便我可以打印竞争对手的数字主要方法,并为竞争对手调用适当的权重(之前在if / then循环中编译)。注意,我目前没有尝试打印竞争对手的重量。
我相信我在这方面正确,但出于某种原因,在调用排序方法后打印的数字不正确。如果你能告诉我我做错了什么,那将会非常有帮助。感谢。
import java.io.*;
import java.util.Scanner;
public class Project8
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner inF = new Scanner(new File("data7.txt"));
PrintWriter outF = new PrintWriter(new File("pro7out.txt"));
int [] arrayNum = new int[7];
int [] sortedNum = new int[7];
double [] arrayWeight = new double[7];
int place, firstplace, lastplace;
double weight;
String line;
String entries[];
outF.printf("My name - Project 7: 4/10/18%nResults of the Rocking JR Fishing Contest%n");
outF.printf("Competitor Total%n Number Weight%n");
for (int m = 0; m < 7; m++)
{
arrayNum[m] = m + 1;
}
while (inF.hasNextLine())
{
line = inF.nextLine();
entries = line.split(" +");
place = Integer.parseInt(entries[0]);
weight = Double.parseDouble(entries[1]);
if (place == 1)
arrayWeight[0] += weight;
else if (place == 2)
arrayWeight[1] += weight;
else if (place == 3)
arrayWeight[2] += weight;
else if (place == 4)
arrayWeight[3] += weight;
else if (place == 5)
arrayWeight[4] += weight;
else if (place == 6)
arrayWeight[5] += weight;
else
arrayWeight[6] += weight;
}
for (int k = 0; k < 7; k++)
outF.printf("%5d %15.2f%n", arrayNum[k], arrayWeight[k]);
firstplace = first(arrayNum, arrayWeight);
lastplace = last(arrayNum, arrayWeight);
sortedNum = sort(arrayNum, arrayWeight);
outF.printf(" Winner is%n %d %3.2f%n", firstplace, arrayWeight[firstplace-1]);
outF.printf(" Not as successful%n %d %3.2f%n", lastplace, arrayWeight[lastplace-1]);
for (int k = 0; k < 7; k++)
outF.printf("%d", sortedNum[k]);
outF.printf(" Contest Over%n");
inF.close();
outF.close();
}
public static int first(int number[], double weight[])
{
int firstplace=0;
double max=0;
for (int k = 0; k < 7; k++)
{
if (weight[k] > max)
{
max = weight[k];
firstplace = number[k];
}
}
return firstplace;
}
public static int last(int number[], double weight[])
{
int lastplace=0;
double minimum=weight[0];
for (int k = 0; k < 7; k++)
{
if (weight[k] < minimum)
{
minimum = weight[k];
lastplace = number[k];
}
}
return lastplace;
}
public static int[] sort(int number[], double weight[])
{
int n = number.length;
int tempNum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 1; j < (n-1); j++)
{
if (weight[j - 1] < weight[j])
{
tempNum = number[j - 1];
number[j - 1] = number[j];
number[j] = tempNum;
}
}
}
return number;
}
}