2
此程序是我的類的最終作業,我有問題找出爲什麼我收到錯誤「從內部類引用的局部變量必須是最終或有效的最終「。該程序正在運行併發線程來對#的數組進行排序,然後查找該數組的高位和低位值。當我沒有併發地創建它時,我沒有這個錯誤。我正在努力確定高低變量的最終定位。從內部類引用的局部變量必須是最終的或有效的最終
public void HiLo(int[] numbers){
int high = numbers[0];
int low = numbers[0];
Runnable r2 = new Runnable(){
@Override
public void run() {
System.out.println("The highest value is: ");
for (int index = 1; index < numbers.length; index++){
if (numbers[index] > high)
high = numbers[index];
System.out.println(high);
}
System.out.println();
System.out.println("The lowest value is: ");
for (int ind = 1; ind < numbers.length; ind++){
if (numbers[ind] < low)
low = numbers[ind];
System.out.println(low);
}
}
};
pool.execute(r2);
}
這是產生錯誤的代碼塊。如果我使int high =數字[0];或int low = numbers [0];最後,我得到一個錯誤,我不能使這個值最終和相反變量的錯誤消失。
下面是該程序的其餘部分。任何幫助表示讚賞。
package concurrentthread;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ConcurrentThread {
static Executor pool = Executors.newFixedThreadPool(2);
public static void main(String[] args) {
int size;
Scanner keyboard = new Scanner(System.in);
ConcurrentThread sort = new ConcurrentThread();
ConcurrentThread hilo = new ConcurrentThread();
System.out.println("This program will calculate the highest and lowest "
+ "numbers entered by the user \nand also sort them in "
+ "ascending order");
System.out.println();
System.out.print("How many numbers would you like in the array? ");
size = keyboard.nextInt();
final int[] numbers = new int[size];
for (int index = 0; index < numbers.length; index++){
System.out.print("Please enter a number between 1 and 100: ");
numbers[index] = keyboard.nextInt();
}
System.out.println();
sort.Sort(numbers);
hilo.HiLo(numbers);
//System.exit(0);
}
public void Sort(int[] numbers){
int sort = numbers[0];
Runnable r1 =() -> {
Arrays.sort(numbers);
System.out.println("The sorted values are: ");
for (int index = 0; index < numbers.length; index++)
System.out.print(numbers[index] + " ");
System.out.println();
};
pool.execute(r1);
}
public void HiLo(int[] numbers){
final int high = numbers[0];
int low = numbers[0];
Runnable r2 = new Runnable(){
@Override
public void run() {
System.out.println("The highest value is: ");
for (int index = 1; index < numbers.length; index++){
if (numbers[index] > high)
high = numbers[index];
System.out.println(high);
}
System.out.println();
System.out.println("The lowest value is: ");
for (int ind = 1; ind < numbers.length; ind++){
if (numbers[ind] < low)
low = numbers[ind];
System.out.println(low);
}
}
};
pool.execute(r2);
}
}
非常感謝您的幫助,這確實有效。我覺得這是一件小事,必須加以調整。 – Bails