这是我在这个网站上的第一个问题,我在 NetBeans 8.0.2 上运行它并尝试打印出我的用户定义的数组,但它一直返回空值。例如,如果你说有 2 名员工并输入他们的名字,它将返回 [null, null]
如何修复这个错误?我是新手。
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// counter for the if statement that should return all employees from the array
int counter = numberOfEmps;
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
}
}
忽略 import java.text.DecimalFormat,因为我计划稍后在我的代码中使用此导入。预先感谢任何善良/聪明的回复者。
最佳答案
首先,您从未将 nameCycler
放入数组中。其次,您每次迭代都会创建 namesArray
,我认为这是错误的。
关于java 用户定义的数组(和用户定义的数组大小)返回 [null, null, null, ...],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32197513/