【发布时间】:2016-01-30 06:25:41
【问题描述】:
我想我几乎已经搞定了我的 java 程序。它旨在通过使用 10 个不同的线程读取文本文件并找到最大的整数。我收到了这个错误:
Error:(1, 8) java: class Worker is public, should be declared in a file named Worker.java
我觉得我的代码可能比它需要的更复杂,所以我试图弄清楚如何缩小它的大小,同时修复上面的错误。非常感谢您在此问题上提供的任何帮助,如果我能澄清任何事情,请告诉我。另外,“工人”类是否必须是一个单独的文件?我将它添加到同一个文件中,但出现上述错误。
import java.io.BufferedReader;
import java.io.FileReader;
public class datafile {
public static void main(String[] args) {
int[] array = new int[100000];
int count;
int index = 0;
String datafile = "dataset529.txt"; //string which contains datafile
String line; //current line of text file
try (BufferedReader br = new BufferedReader(new FileReader(datafile))) { //reads in the datafile
while ((line = br.readLine()) != null) { //reads through each line
array[index++] = Integer.parseInt(line); //pulls out the number of each line and puts it in numbers[]
}
}
Thread[] threads = new Thread[10];
worker[] workers = new worker[10];
int range = array.length / 10;
for (count = 0; count < 10; count++) {
int startAt = count * range;
int endAt = startAt + range;
workers[count] = new worker(startAt, endAt, array);
}
for (count = 0; count < 10; count++) {
threads[count] = new Thread(workers[count]);
threads[count].start();
}
boolean isProcessing = false;
do {
isProcessing = false;
for (Thread t : threads) {
if (t.isAlive()) {
isProcessing = true;
break;
}
}
} while (isProcessing);
for (worker worker : workers) {
System.out.println("Max = " + worker.getMax());
}
}
}
public class worker implements Runnable {
private int startAt;
private int endAt;
private int randomNumbers[];
int max = Integer.MIN_VALUE;
public worker(int startAt, int endAt, int[] randomNumbers) {
this.startAt = startAt;
this.endAt = endAt;
this.randomNumbers = randomNumbers;
}
@Override
public void run() {
for (int index = startAt; index < endAt; index++) {
if (randomNumbers != null && randomNumbers[index] > max)
max = randomNumbers[index];
}
}
public int getMax() {
return max;
}
}
【问题讨论】:
-
“解析时 EOF”问题是由源代码文件末尾的杂散 cloiseng 大括号
}引起的。 -
我也遇到了这个错误。我在工人阶级中固定了右括号。错误:(58, 1) java: 需要类、接口或枚举
-
工人阶级的右大括号很好。
readTextFile类的末尾有太多右大括号 -
至于你问题的另一部分。有一个专门针对 Code Review 的 SE 网站,所以您最好去那里询问
-
哦,等等,我修复了一个愚蠢的变量错误,并修复了右括号。我现在收到这个新错误。请参见上文。
标签: java multithreading algorithm syntax logic