简体   繁体   中英

Changing a variable outside a for loop from within the loop

In this situation an array nums has an undefined amount of integers in it and I'm trying to find the largest and print it. When I do this a is always printed as 0 because whatever is happening in the loop doesn't affect the a value outside of it. Anyone know how to fix this?

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

This code has two errors:

  1. the loop will never execute since i will start with a value less than nums.length
  2. you increment the loop index twice!

Your loop should look like this:

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

Here is a solution for your problem:

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM