当前位置: 动力学知识库 > 问答 > 编程问答 >

Java For Loop Can't Increment

问题描述:

I've been trying to make the System.out.println in the first For loop of class InputArray to say "Enter the 1st integer", "Enter the 2th ineger", "Enter the 3th integer", etc until the 5th.

import java.util.Scanner ;

class InputArray

{

public static void main ( String[] args )

{

int[] array = new int[5]; //5 elements 4 indexs

int data;

Scanner scan = new Scanner( System.in );

// input the data

for (int index=0; index <array.length; index++)

{

//I tired x=0 here with x++ after this line to increase x until 5.

System.out.println( "enter the integer: " );

//I also tried changing the previous line to:

//System.out.println( "Enter the " + (count+1) + "th integer" );

data = scan.nextInt();

array[ index ] = data ;

}

for (int index=0; index <array.length; index++)

{

System.out.println("array ["+index+"] = "+array[index]);

}

}

}

But this just results in "Enter the 1th integer" for all 5 outputs. The second For loop in class InputArray works but I noticed its because variable index is being incremented in the header. This while loop in another program doesn't have that problem.

import java.util.Scanner;

public class AddUpNumbers1

{

public static void main (String[] args )

{

Scanner scan = new Scanner( System.in );

int value; // data entered by the user

int sum = 0; // initialize the sum

int count = 0; // number of integers read in

System.out.print( "Enter first integer (enter 0 to quit): " );

value = scan.nextInt();

while ( value != 0 )

{

//add value to sum

sum = sum + value;

// increment count

count = count + 1;

//get the next value from the user

System.out.println( "Enter the " + (count+1) + "th integer (enter 0 to quit):" );

value = scan.nextInt();

}

System.out.println( "Sum of the integers: " + sum );

}

}

Is there a way around this? Do for loops only increment variables within their headers?

网友答案:

In reality a for loop such as:

for(<initialization>; <condition>; <afterthought>) {
   <action>
}

would act as the following pseudocode suggests.

while(condition is satisfied)
  perform action
  afterthought

So, given that you have the following for loop:

for(int i = 0; i < 100; i++) {
   someFunction();
}

After initialization (which is defining the variable index and setting it to zero), condition will be checked. If satisfied, someFunction will get called with i=0, then i will increment.

In a while loop, however, you have control over this, you can increment before you perform that loop action or increment at the end or any time you want. I'd personally would suggest using while loops when dealing with enumerators like that. But that's just me and for loops are just as good.

More info on for loops: https://en.wikipedia.org/wiki/For_loop

分享给朋友:
您可能感兴趣的文章:
随机阅读: