首页 > 解决方案 > 在java中打印数组中的每个单词

问题描述

public class namePrinting 
{
    //each name in a series of names
    public String[] names = {"Hello", "My", "Name", "Is", "Jose"};

    //the method for putting names in 
    public static void printNames(String [] namesArray) 
    {
        //go through each String in the array and then print each
        for(int i = 0; i <= namesArray.length; i++)
        {
            System.out.println(namesArray[i]);
        }
    }
    //print the names in this specific array
    printNames(names[]);
}

我对Java很陌生,想知道我做错了什么?我只想遍历数组中的每个字符串并打印每个字符串。我认为不正确的部分在底部......是否有一个我忘记放入 printNames 的特定变量?

标签: java

解决方案


您的代码包含多个错误:

  1. names在静态方法中使用数组,但名称本身不是静态的。从方法中删除静态,或将静态添加到字段。
  2. printNames(names[]);是在班级级别,这是不可能的。方法调用应该在方法或构造函数中。
  3. names[]因为参数输入也无效。这应该是printName(names)相反的。
  4. <=应该是<。因为数组的长度为 5,但索引为 [0-4]。

尝试这样的事情(没有静态):

public class NamePrinter
{
    //each name in a series of names
    public String[] names = {"Hello", "My", "Name", "Is", "Jose"};

    //the method for putting names in 
    public void printNames(String [] namesArray) 
    {
        //go through each String in the array and then print each
        for(int i = 0; i < namesArray.length; i++)
        {
            System.out.println(namesArray[i]);
        }
    }

    public static void main(String[] a){
        NamePrinter namePrinter = new NamePrinter();

        //print the names in this specific array
        namePrinter.printNames(namePrinter.names);
    }
}

在线尝试。

或者使用静态:

public class NamePrinter
{
    //each name in a series of names
    public static String[] names = {"Hello", "My", "Name", "Is", "Jose"};

    //the method for putting names in 
    public static void printNames(String [] namesArray) 
    {
        //go through each String in the array and then print each
        for(int i = 0; i < namesArray.length; i++)
        {
            System.out.println(namesArray[i]);
        }
    }

    public static void main(String[] a){
        //print the names in this specific array
        printNames(names);
    }
}

在线尝试。


推荐阅读