简体   繁体   中英

Why is my for loop not exiting?

First time working with arrays. I think I've figure out the beginning of establishing the array but I'm having a problem with one of my loops not kicking out and I don't why. My loop of "days" keeps restarting after hitting 10. Any help would be appreciated. Thanks

public class TempArray
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        double sumOfTemps = 0.0;
        double [] temperatures = new double[10];        
        for(int index = 0; index <= 10; index++){
            for(int days = 1; days <= 10; days++){
                System.out.print("Enter the temperature for day " + days + " : ");
                temperatures[index] = keyboard.nextDouble();
                sumOfTemps = sumOfTemps + temperatures[index];

Your program will end, but because of first loop you start second loop 10 times. So you have to type 100 temperatures.

I don't know that you are trying to achieve, but if you want to provide only 10 temperatures, get rid of the first loop and leave only the second one.

In addition to my 2nd comment, you probably want something like this:

for(int days = 0; days < 10; days++) {
    System.out.print("Enter the temperature for day " + (days+1) + " : ");
    temperatures[day] = keyboard.nextDouble();
    sumOfTemps = sumOfTemps + temperatures[day];
}

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