gpt4 book ai didi

java - 如何计算 Java 数组用户输入的字符数?

转载 作者:行者123 更新时间:2023-12-01 19:34:13 26 4
gpt4 key购买 nike

Help 我想知道用户在这段程序代码中输入了多少个字符。

此代码要求用户输入 5 个名称并知道该名称有多少个字符。我尝试使用 for 循环计数器来输出所使用的字符。

是否可以使用此代码的方法?我很困惑。 :(

import java.util.Scanner;

public class ArrayDec2_Baban{
public static void main(String [] args){
int ctr=0;
String arrayname [] = new String [5];
Scanner in = new Scanner(System.in);

System.out.println("This program will require you to input 5 names where each name will be counted and the length of each name will be displayed.");
System.out.println("Please enter 5 names: ");

for (int i=0;i<=4;i++){
arrayname [i] = in.nextLine();
}

System.out.println();

for (int i=0;i<=4;i++){
System.out.println(arrayname[i]);
}

for(int i = 0 ; i < arrayname.length; i++){
char [] name = arrayname[i].toCharArray();
for(int j = 0,count = 0 ; j <= name.length; j++){
if (Character.isLetter(name[j])) {
ctr++;
}
System.out.println(ctr);
}
}
}
}

我觉得我的 body 状况有问题或者有什么问题。请帮忙。谢谢。

最佳答案

您可以从字符串中删除所有非字母字符,然后使用 length 返回字符串中的字母数。

int[] count = new int[arrayname.length];
for(int i = 0 ; i < arrayname.length; i++){
count[i] = arrayname[i].replaceAll("[^a-zA-Z]", "").length();
}
//count[0] holds the size of the first name
//count[1] holds the size of the second name
//...

关于java - 如何计算 Java 数组用户输入的字符数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236098/

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