gpt4 book ai didi

java - 大写、小写等计数器

转载 作者:行者123 更新时间:2023-11-29 05:14:21 26 4
gpt4 key购买 nike

所以我一直在用 Java 编写一小段代码,它从用户那里获取输入,计算大写字母、小写字母和其他部分(例如空格、数字,甚至括号),然后返回每个部分的数量用户。

我遇到的问题是,如果我输入“Hello There”,它会停止计算 Hello 中“o”之后的点数。所以在第一个词之后。

代码

import java.util.Scanner;

public class Example {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}

最佳答案

Scanner#next :

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

问题是 next 没有看到单词“There”,因为“Hello World”不是一个完整的标记。

next 更改为 nextLine .

建议:使用调试器,您会很快找到问题,当您有疑问时,请参阅文档,它们就在您身边。

关于java - 大写、小写等计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27127780/

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