问题是:
a program prompts the user to enter a list of six positive integers, and then declares an array of six elements. The program should sort the list’s elements in ascending order. In addition, the program should display both the original and the sorted list.
我的代码是:
import java.util.*;
public class q2 {
static Scanner scan = new Scanner (System.in);
public static void main (String[] args ) {
int i;
int [] fList = new int [6];
int [] sList = new int [6];
System.out.println ("Enter 6 positive integers :");
for ( i=0 ; i<fList.length ;i++)
fList[i]=scan.nextInt();
for( i=0 ; i<fList.length ; i++)//to copy
fList=sList;
int min;
{
for ( i=0;i<sList.length ; i++)//sort
min = i ;
for (int j=i+1 ; i<sList.length ; i++)
if (sList[j] < sList[min] )
min=j;
int temp=sList[i];
sList[i]=sList[min];
sList[min]=temp;
}
System.out.println("Original array : ");
for ( i=0 ; i < fList.length ; i++)
System.out.println(fList[i] + " ");
System.out.println();
System.out.println("Array after sorting :");
for ( i=0 ; i < sList.length ; i++)
System.out.println(sList[i] + " ");
}
}
它说:
q2.java:23: variable min might not have been initialized if (sList[j] < sList[min] ) ^ q2.java:27: variable min might not have been initialized sList[i]=sList[min]; ^ 2 errors
虽然我已经初始化了它
最佳答案
int min;
您尚未初始化min
。我可以看到您已经在 for
循环中完成了 min = i ;
,但这仍然是有条件的(for
可能并不总是执行,假设在这种情况下,数组是空的),这就是编译器这么说的原因。您需要使用默认值初始化它
int min = 0;
或者在任何 if
或 for
或任何条件语句之外为其分配一些值。
关于java - 变量尚未初始化,而我已经初始化了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945745/