java - 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("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++)
推荐阅读
- python - 尽管已经在 INSTALLED_APPS 中,但 Django 无法导入“main_app”
- python - python注释函数,将参数传递给另一个函数
- c# - 如何将扩展加载到 CefSharp 浏览器?
- charts - Flutter Graphview
- user-interface - Tcl 文本:如何以编程方式移动插入点?
- html - 如何在 v-for 循环中拖动单个元素
- flutter - 仅音频中的自定义操作通知图标
- java - 线程池如何能够重用线程?
- java - How to use Jackson to parse XML files with streaming API
- c# - 多层解决方案中的 Blazor 应用程序管理授权