java 用户定义数组(和用户定义数组大小)返回 [null, null, null, ...]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32197513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:48:30  来源:igfitidea点击:

java user-defined array (and user-defined array size) returning [null, null, null, ...]

javaarraysnulluser-defined

提问by Ryan Horner

This is my first question on this site, I'm running this on NetBeans 8.0.2 and trying to print out my user-defined array but it keeps returning null values. For example if you say there are 2 employees and enter both of their names, it will return [null, null]

这是我在此站点上的第一个问题,我在 NetBeans 8.0.2 上运行它并尝试打印出我的用户定义数组,但它一直返回空值。例如,如果您说有 2 个员工并输入他们的姓名,它将返回 [null, null]

How to fix this error? I'm a novice.

如何修复此错误?我是新手。

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));
        }
    }
}
}

Disregard import java.text.DecimalFormat as I plan to use this import later on in my code. Thank you in advance to anyone who is kind/smart enough to respond.

忽略 import java.text.DecimalFormat 因为我打算稍后在我的代码中使用这个导入。提前感谢任何善良/聪明的人来回应。

回答by wawek

First of all you never put your nameCyclerto array. Second of all you create your namesArrayevery iteration which I think is wrong.

首先,你从来没有把你nameCycler的数组。其次,你创建你的namesArray每一次迭代,我认为这是错误的。

回答by chrylis -cautiouslyoptimistic-

You're creating a brand new (full of null) array namesArrayon every passthrough the loop--and then never assigning anything to it. I think you're looking for something like this instead. Note that Java indexes from zero, not one.

您在每次通过循环时都创建了一个全新的(充满null)数组——然后从不为其分配任何内容。我认为你正在寻找这样的东西。请注意,Java 索引从零开始,而不是从一开始。namesArray

String[] names = new String[numberOfEmps]

for(int i = 0; i < names.length; i++) {
    names[i] = scanner.next();
}

System.out.println(Arrays.toString(names));

回答by Matthias A. Eckhart

First of all, you should initialise the array outside of your loop. Secondly, you forgot to set the name to the array value(s).

首先,您应该在循环之外初始化数组。其次,您忘记将名称设置为数组值。

Try this:

试试这个:

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();

        int[] nOEarray = new int[numberOfEmps];

        System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");

        String[] namesArray = new String[numberOfEmps];

        for (int i = 0; i < numberOfEmps; i++) {
            namesArray[i] = scan.next();
        }
        System.out.println(Arrays.toString(namesArray));
    }
}

回答by Naman Gala

Added comments in the code to point out changes.

在代码中添加了注释以指出更改。

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();

    // removed 'nOEarray' and 'counter'

    if (numberOfEmps > 0) {
        System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");

        // initializing 'namesArray' outside for loop.
        String[] namesArray = new String[numberOfEmps];
        for(int i = 0; i < numberOfEmps; i++) { // initialized with 0 and updated condition with '<'
            namesArray[i] = scan.next(); // assigning value to 'i'th position of namesArray
        }
        System.out.println(Arrays.toString(namesArray)); // Printing array outside for loop
    }
}

回答by Ferdinand Neman

Replace

代替

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));
    }
}

With

String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++)
{
    namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));

And see whether it works.

看看它是否有效。

回答by Jens

You never assign the name to the array and in every iteration you define the array new:

您永远不会将名称分配给数组,并且在每次迭代中都定义新的数组:

 String[] namesArray = new String[numberOfEmps];
 for(int i = 1; i <= numberOfEmps; i++)
    {
        String nameCycler = scan.next();
        namesArray [i] = nameCycler ;
        if(counter == i)
        {
            System.out.println(Arrays.toString(namesArray));
        }
    }

回答by Stultuske

"How to fix this error" not. This is not an error.

“如何修复此错误”不是。这不是错误。

 String[] namesArray = new String[i]; // step one, you declare an array of Strings
  // which you don't initialize

        if(counter == i)
        {
            System.out.println(Arrays.toString(namesArray));
//you print all the (non-initialized) elements of namesArray
//since you didn't initialize the elements, it takes the default value, which is null
        }

fill the elements of the array with Strings before trying to print them.

在尝试打印它们之前用字符串填充数组的元素。