gpt4 book ai didi

java - 如何打印数组?

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:07 25 4
gpt4 key购买 nike

我的练习几乎已经完成,只是我似乎不知道如何显示数组。做法是从用户那里取出一组长度为10的字符串,检查字符串中是否有0-9的数字与长度为10的数组对应。

这就是我到目前为止所拥有的。

import java.util.*;

public class CharacterFrequency {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int telNumber[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

System.out.print("Give me a word of 10 characters. "
+ "\nI will tell you if it contains any numbers, and how many: ");
String word = keyboard.nextLine();
int length = word.length();
if (length < 10 || length > 10) {
System.out.println("Wrong length, you have entered an invalid word.");
System.exit(0);
} else {


for (int index = 0; index < word.length() - 1; index++) {
char ch = word.charAt(index);
if ('0' == ch) {
telNumber[0]++;
} else if ('1' == ch) {
telNumber[1]++;
} else if ('2' == ch){
telNumber[2]++;
} else if ('3' == ch){
telNumber[3]++;
} else if ('4' == ch){
telNumber[4]++;
}else if ('5' == ch){
telNumber[5]++;
}else if ('6' == ch){
telNumber[6]++;
} else if ('7' == ch){
telNumber[7]++;
} else if ('8' == ch){
telNumber[8]++;
}else if ('9' == ch){
telNumber[9]++;
} else {
System.out.println("\nWrong length, you have entered an invalid word.");
System.exit(0);
}
}
System.out.println();

}
}
}

我不知道如何打印出如下所示的输出:

0的个数为(字符串中0的个数)

1 的个数为(字符串中 1 的个数)

2 的个数是(字符串中 2 的个数)

3 的个数是(字符串中 3 的个数)

4 的计数是(字符串中 4 的数量)等等

最佳答案

打印 int 数组的最简单方法通常是 Arrays.toString(int[])

System.out.println(Arrays.toString(telNumber));

您的 telNumber 声明应该看起来更像,

int telNumber[] = new int[10]; // {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

您的声明为每个元素提供了等于其索引的初始计数(我相当确定您希望它们为零)。然后,要获取您要求的格式(使用 printf()for 循环)可能看起来像

for (int i = 0; i < telNumber.length; i++) {
System.out.printf("Count of %d is %d%n", i, telNumber[i]);
}

最后,使用 Character.digit(char, int) 可以显着缩短您的长 if else 链。喜欢

if (ch >= '0' && ch <= '9') {
telNumber[Character.digit(ch, 10)]++;
} else {
System.out.println("\nWrong length, you have entered an invalid word.");
System.exit(0);
}

关于java - 如何打印数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com