java - 变量尚未初始化,而我已经初始化了

标签 java arrays

问题是:

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;

或者在任何 iffor 或任何条件语句之外为其分配一些值。

关于java - 变量尚未初始化,而我已经初始化了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945745/

相关文章:

java - spring boot循环依赖设计问题

java - 如何在java中实现循环双向链表add方法

java - Java 中的顺序字符串搜索

Java:外部类和内部类方法之间的名称歧义

c++ - std::array 作为虚函数中的参数

java - 如何在 SQLData.writeSQL() for Oracle 中将 java.sql.Array 写入 java.sql.SQLOutput

c++ - 创建一批随机矩阵

java - 为什么数组中的最后一个元素会覆盖所有先前的元素?

PHP:如何替换数组中的最后 X 个元素

java - 在Jmeter中提取数组中的json