我目前正在开发程序,无法弄清楚为什么每次打印长度时都无法打印出正确的数字。大写和小写都可以正常工作。
示例输入为:
我
爱
编程
输出将是:
字符数为16。
小写字母的数目为13。
大写字母的数目为3。
databaseAccess.open();
mEntry = databaseAccess.getEntry();
databaseAccess.close();
mEntryAdapter = new EntryAdapter(this,
R.layout.entry_item, mEntry);
this.mEntryListView.setAdapter(mEntryAdapter);
答案 0 :(得分:0)
每个循环都使用当前行的长度覆盖length变量。您应该更改的是将当前行的长度添加到总计中。因此,请同时删除您的length = s.length();
和一个length += s.length();
语句。我假设您不想计算换行符。参见下面的代码:
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();
System.out.println("new length = " + length);
char[] charAnalysis = s.toCharArray();
for (char element : charAnalysis) {
if (Character.isUpperCase(element)) {
uppercase++;
}
else if (Character.isLowerCase(element)) {
lowercase++;
}
}
}
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) {
System.out.println(e.getMessage());
}
}