Java:我做了一个程序,它接受整数数组的输入并在表中显示值。尝试使用字符串数组重新创建它。请帮助,



Java是我的第一门编程语言,我仍然不熟悉数组的工作原理。但是,我能够制作这个程序,它接受整数数组的用户输入;然后,它输出索引和值,以显示数组如何存储数字。我想使用字符串数组重新创建这个程序,以创建一个包含朋友列表的表。

.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("IndexttValue");
        for (int count2=0; count2<arrayInput.length; count2++)
            System.out.println(" [" + count2 + "]"+"tt  " + 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("Femalettt" + "Malettt" + "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("ttt" + arrayOfFriendsMale[countM2]);
            for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
                System.out.println("tttttt" +arrayOfFriendsAliens[countA2]);
    }
}

.length属性存储数组中的元素数。但是元素是从0开始的.因此,当.length = 1 ,则数组中只有一个元素,索引为 0

似乎在 for 循环中的字符串数组程序中,<=应该更改为 <

喜欢这个:

 for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)

相关内容

  • 没有找到相关文章

最新更新