我想我已经很接近了,但目前我陷入困境。 基本上我需要做的是要求 3 个字符串,并从输入中找到小写字母的较低数量和小写字母的最高数量
import java.util.*;
public class Practice_program1 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int x = 0;
int y = 0;
int z = 0;
String user;
String a = input.nextLine();
String b = input.nextLine();
String c = input.nextLine();
for (int i = 0; i < 3; i++) {
System.out.print("Enter a String: ");
user = input.nextLine();
if (Character.isLowerCase(a.charAt(i)))
x++;
else if (Character.isLowerCase(b.charAt(i)))
y++;
else if (Character.isLowerCase(c.charAt(i)))
z++;
{
if (x > y && x > z)
;
System.out.print(user + " has the highest number of lowercase letters" + a);
if (y > z && y < x)
;
System.out.print(user + " has the lowerst number of lowercase letters" + b);
}
}
}
}
最佳答案
嗯,在提供解决方案之前我想指出一些事情。
- 我不明白字符串变量“user”的用法。因此,我跳过了它。如果您可以解释其用法,我可以根据需要相应地编辑代码。
- 不考虑两个字符串具有相同数量小写字母的情况。
- 另一件事是,您尝试使用迭代变量 i 来计算小写字母的数量,但是如果字符串具有三种不同的长度怎么办?
这就是为什么我认为最好编写一个单独的方法来计算每个字符串中小写字母的数量,然后比较它们的计数以找到具有最大小写字母和最小小写字母的字符串。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user;
String a = input.nextLine();
String b = input.nextLine();
String c = input.nextLine();
input.close();
int countOfA = findLowerCaseNumber(a);
int countOfB = findLowerCaseNumber(b);
int countOfC = findLowerCaseNumber(c);
if(countOfA > countOfB && countOfA > countOfC){
System.out.println(a + " has the highest number of lowercase letters " + countOfA );
if(countOfB < countOfC)
System.out.println(b + " has the lowest number of lowercase letters " + countOfB );
else
System.out.println(c + " has the lowest number of lowercase letters " + countOfC );
}
else if(countOfB > countOfA && countOfB > countOfC){
System.out.println(b + " has the highest number of lowercase letters " + countOfB );
if(countOfA < countOfC)
System.out.println(a + " has the lowest number of lowercase letters " + countOfA );
else
System.out.println(c + " has the lowest number of lowercase letters " + countOfC );
}
else {
System.out.println(c + " has the highest number of lowercase letters " + countOfC );
if(countOfB < countOfC)
System.out.println(b + " has the lowest number of lowercase letters " + countOfB );
else
System.out.println(a + " has the lowest number of lowercase letters " + countOfA );
}
}
public static int findLowerCaseNumber(String str){
int lowerCaseLetters = 0;
for(int i = 0; i < str.length(); i++)
// I prefer to use the ASCII values of lower case letters but what you have used is also correct.
if(str.charAt(i) > 96 && str.charAt(i) < 123)
lowerCaseLetters++;
return lowerCaseLetters;
}
您还可以使用 nullpointer 提到的 Math.max() 和 Math.min() 来导出解决方案,而不是手动比较每个字符串的计数。
关于java - 查找小写单词的最大和最小数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143548/