【发布时间】:2018-10-12 21:04:07
【问题描述】:
我目前正在开发一个程序,但无法弄清楚为什么每当我打印长度时它没有打印出正确的数字。大写和小写都可以正常工作。
一个示例输入是:
我
爱
编程
然后输出将是:
字符数为 16。
小写字母个数为 13。
大写字母的个数为 3。
public static void main(String[] args) throws IOException
{
int lowercase = 0;
int uppercase = 0;
int length = 0;
File file1 = new File("input.txt");
Scanner scanner = new Scanner(file1);
while(scanner.hasNext())
{
String s = scanner.nextLine();
length = s.length();
char[] charAnalysis = s.toCharArray();
for (char element : charAnalysis)
{
if (Character.isUpperCase(element))
{
uppercase++;
}
else if (Character.isLowerCase(element))
{
lowercase++;
}
length = s.length();
}
}
File file2 = new File("output.txt");
try (PrintStream ps = new PrintStream(file2))
{
ps.println("Number of characters is " + length);
ps.println("Number of lower case letters is " + lowercase);
ps.println("Number of upper case letters is " + uppercase);
}
catch(IOException e)
{
}
}
}
【问题讨论】:
-
"...当我打印长度时,它不会打印出正确的数字" 你认为正确的数字是多少?你看到了什么呢?为什么你认为代码会产生第一个?当您使用 IDE 中内置的调试器运行此程序时,您会看到什么? (使用调试器不是高级技能。它基本上是您在“Hello, world”之后应该学习的第一件事,并且在学习编程时难以置信非常有用。)
标签: file input java.util.scanner counting string-length