java - 在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 的特定变量?
解决方案
您的代码包含多个错误:
- 您
names
在静态方法中使用数组,但名称本身不是静态的。从方法中删除静态,或将静态添加到字段。 printNames(names[]);
是在班级级别,这是不可能的。方法调用应该在方法或构造函数中。names[]
因为参数输入也无效。这应该是printName(names)
相反的。<=
应该是<
。因为数组的长度为 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);
}
}
推荐阅读
- android - 在 Android Studio 中更改新 AVD 的默认位置?
- gatsby - Gatsby 将字符串转换为相对路径
- c++ - 如何在控制台应用程序中为文本着色?
- c# - 使用 SSH.NET SFTP 执行 sudo 以访问文件
- powershell - 如何使用 Powershell 从 json 属性中获取键值对
- java - 类文件的版本错误 55.0,应该是 52.0 (IntelliJ)
- angular - 在 Angular 组件中使用被覆盖的 SCSS 变量的正确方法
- .net - .NET 源链接:尽管链接正确,但“找不到源”
- python - 相同 x 轴值的不同条形图
- json - Kotlin 序列化对于这种类型的数据结构?