【问题标题】:How can i fix the error so that i could use insertion sort如何修复错误以便我可以使用插入排序
【发布时间】:2020-12-08 18:41:08
【问题描述】:

我试图创建一个随机数组,该数组接受用户输入并打印该数量的随机值

例如,如果我输入 5,它将创建一个 [3,4,5,6,6] 的数组

然后我尝试使用插入排序,以便它可以按照正确的顺序从最小值到最大值重新排列值,但是我一直收到此错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    j cannot be resolved to a variable

那个错误就在result[j+1] = key;

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Size of Random Number");
        int n = input.nextInt(); 
        Random random = new Random(); 
        int[] result = random.ints(n, 0, 10).toArray();
        Arrays.stream(result).forEach(System.out::print);
        System.out.println("\n");
        
       
        int len = result.length;
        for(int i=1; i<len; i++) {
            int key = result[i];
            for (int j=i-1; (j >= 0 && result[j] > key); j--) { 
                result[j + 1] = result[j];  
            }  
            result[j+1] = key;
            System.out.println(Arrays.toString(result));
        }
    }
    }

【问题讨论】:

  • j 只存在于声明它的循环中。
  • 我试图把它放回循环中,但是它不会做插入排序
  • 如果你在循环外需要它,那么在循环外声明它。

标签: java for-loop debugging insertion-sort


【解决方案1】:
for(int i=1; i<len; i++) {
        int key = result[i];
        int j;
        // you should declare a variable outside of the for loop in such cases,
        // because if you declare it within the for loop it will be locally scoped within that for loop and not available outside it.
        for (j=i-1; (j >= 0 && result[j] > key); j--) {
            result[j + 1] = result[j];
        }
        result[j+1] = key;
        System.out.println(Arrays.toString(result));
    }

您可以阅读更多关于范围here 的信息。

  1. 循环范围

如果我们在循环内声明一个变量,它将有一个循环范围,并且只能在循环内使用:

【讨论】:

  • 嗨@Manuj,请更新您的答案以包含您引用的页面的报价 - 因此,如果该页面丢失,您尝试建议的见解不会丢失。
  • 您好,感谢您的反馈,我没有使用页面中的引用,如果他们想了解更多关于 java 中范围的信息,我就把它留在那里。
猜你喜欢
  • 2019-11-01
  • 2020-11-08
  • 2019-11-12
  • 2019-08-15
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
相关资源
最近更新 更多