首页 > 解决方案 > 当我使用 Java 时,程序会跳过数组中的一个值

问题描述

由于数组从零开始,如何添加最后一个值?

import java.util.*;

public class Main{
    public static void main(String[]args)
    {
        Scanner x = new Scanner (System.in);
        System.out.print("Enter the number of players: ");
        int numplay = x.nextInt();
        int players[]= new int[numplay];
        for(int y=0;y<numplay ;y++)
        {
            if(y > 0)
            {
                System.out.print("Goals score by player #"+ y +": ");
                players[y]=x.nextInt();
            }
        }
    }
}

输出:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3

期望的输出:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3
Goals score by player #4: 3

标签: java

解决方案


只需打印y加一的值。

public static void main(String[] args) {
    Scanner x = new Scanner(System.in);
    System.out.print("Enter the number of players: ");
    int numplay = x.nextInt();
    int players[] = new int[numplay];
    for (int y = 0; y < numplay; y++) {
        System.out.print("Goals score by player #" + (y + 1) + ": ");
        players[y] = x.nextInt();
    }
}

通过在对y + 1的调用中放入方括号,printJava 明白这意味着添加操作而不是字符串连接。

运行上面的代码给了我这个输出:

Enter the number of players: 4
Goals score by player #1: 1
Goals score by player #2: 2
Goals score by player #3: 3
Goals score by player #4: 4

推荐阅读