【问题标题】:Changing a variable outside a for loop from within the loop从循环内更改 for 循环外的变量
【发布时间】:2016-10-20 16:30:17
【问题描述】:

在这种情况下,数组 nums 中包含未定义数量的整数,我试图找到最大的并打印它。当我这样做时, a 总是打印为 0 因为循环中发生的任何事情都不会影响它之外的 a 值。有谁知道如何解决这个问题?

int a = 0;
for(int i=0;i>nums.length;i++){
  if(nums[i]>a)
    a=nums[i];
  i++;}
System.out.print(a);

【问题讨论】:

  • 使用 i
  • 每次迭代是否打算将i 加倍?
  • @PavneetSingh:恕我直言,将其作为答案并处理双重 i++ 并没有什么坏处。
  • 当您在调试器中单步执行此代码时,您会看到什么?
  • @Bathsheba,谢谢,我很感激 :)

标签: java loops variables for-loop


【解决方案1】:

这段代码有两个错误:

  1. 循环永远不会执行,因为i 将以小于nums.length 的值开始
  2. 您将循环索引增加两次!

你的循环应该是这样的:

for(int i=0;i<nums.length;i++){
  if(nums[i]>a)
    a=nums[i];
}

【讨论】:

    【解决方案2】:

    以下是您的问题的解决方案:

    import java.util.*;
    
    class Main {
      public static void main(String[] args) {
        List<Integer> arrayList = new ArrayList<Integer>();
        Random r = new Random();
    
        // Fill the ArrayList with integer RandomNumbers
        int size = r.nextInt(100);
        int maxValue = 0;
        for(int i=0 ; i < size ; i++){
            int value = r.nextInt(1000);
            System.out.println("Current value: " + value);
            arrayList.add(value);
            if(value > maxValue)
                maxValue = value;
        }
    
        System.out.println("Max: " + maxValue);
        // If u want to shuffle the list
        Collections.shuffle(arrayList);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2017-06-21
      • 1970-01-01
      相关资源
      最近更新 更多