So i'm trying to write this code which goes into another class to store info but i have a problem with the for loop and i dont know why.
public static void main(String[] args) {
ArrayList<String> Teams = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.printf("Please Enter how many teams?\n");
int x;
x = input.nextInt();
System.out.print(x);
for ( int i=0 ; i>=x ; i++)
{
System.out.printf("Enter the %s Team\n", x);
String temp;
temp = input.next();
Team TeamNamee = new Team(temp);
}
}
Loop should be
for ( int i=0 ; i<=x ; i++)
i
is less than equal to x
Understanding Loop:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
So in your case(Boolean expression is false) i
is not greater than or equal to x(if x is greater than 0 ) for loop is not executed.
Change your for loop like this:
for ( int i=0 ; i<=x ; i++)
instead of
for ( int i=0 ; i>=x ; i++)
Change
for ( int i=0 ; i>=x ; i++)
to
for ( int i=0 ; i<=x ; i++)
so the for loops runs as long as i is smaller or equal to x
for(int i=x; i>=0; i--)
如果要在条件部分中使用“大于”。
Loop must be:
for (int i = 1 ; i <= x ; i++)
if you want start numbering from 1, or
for (int i = 0 ; i < x ; i++)
if you prefer numbering from 0 (in your current loop condition i>=x
is never true
if x > 0
, so your loop never works).
Also expression
System.out.printf("Enter the %s Team\n", x);
looks strange inside the loop, so consider the following
System.out.printf("Enter the %d's Team\n", i);
and for that output numbering from 1 (the first option concerning for
) looks seems to be better.
Change your for loop to: for(int i = 0; i<=x; i++) { }
instead of: for ( int i=0 ; i>=x ; i++) { }
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.