Java 是我的第一门编程语言,我仍然不熟悉数组的工作原理。然而,我能够制作这个程序,它接受用户输入的整数数组;然后它输出索引和值,以显示数组如何存储数字。我想使用字符串数组重新创建这个程序,以制作一个包含 friend 列表的表。
.length 属性也让我困惑......
有人可以解释一下 .length 属性并帮助我使字符串数组程序正常工作吗?
非常感谢。
这是整数数组表程序的工作代码
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
这是我正在处理的字符串数组程序的代码
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
最佳答案
.length
属性存储数组中元素的数量。但元素是从0
开始的。所以,当 .length = 1
,那么数组中只有一个元素,索引为 0
.
似乎在您的字符串数组程序中的 for 循环中 <=
应更改为<
像这样:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)
关于Java:我编写了一个程序,它接受整数数组的输入并在表中显示值。尝试使用字符串数组重新创建它。请。帮助,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53901203/