java - 当我使用 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
解决方案
只需打印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
的调用中放入方括号,print
Java 明白这意味着添加操作而不是字符串连接。
运行上面的代码给了我这个输出:
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
推荐阅读
- python - 根据他人预测新产品的价值?
- dialogflow-es - processing multiple responses from user in dialogflow
- c++ - 尝试将文本文件加载到动态分配的二维数组中时出现“分段错误”错误
- r - 如何重新排序具有特定因子顺序的 ggplot 对象
- kubernetes - 如何生成 cert.pem 和 key.pem 以部署在带有 helm 的 kubernetes 集群中?
- javascript - JavaScript; validateBinaryTree 函数在节点上给出值错误
- directx - 在 RWByteAddressBuffer 上多次调用 InterlockedAdd 会产生意想不到的结果(在 NVidia 上)
- node.js - 无法使用 Node js 在 AWS lambda 函数中将视频文件转换为音频文件
- aframe - 悬停时在框架实体中设置动画
- oracle-cloud-infrastructure - 在 Oracle Cloud Infrastructure Compute 节点上打开端口 80