Write a program that reads a file one character at a time and prints out how many characters are uppercase letters, lowe

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Write a program that reads a file one character at a time and prints out how many characters are uppercase letters, lowe

Post by answerhappygod »

Write a program that reads a file one character at a time and
prints out how many characters are uppercase letters, lowercase
letters, digits, white space, and something else.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Characters
{
public static void main(String[] args) throws
FileNotFoundException
{
Scanner console = new
Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
File inputFile = new
File(inputFileName);
Scanner in = new Scanner(inputFile);
in.useDelimiter("");
int uppercase = 0;
int lowercase = 0;
int digits = 0;
int whitespace = 0;
int other = 0;
char ch;
String line;
Scanner fin = new Scanner(new
File(inputFileName));
while (fin.hasNextLine())
{
line = fin.nextLine();
for (int i = 0; i <
line.length(); i++)
{
ch =
line.charAt(i);
if
(Character.isUpperCase(ch)) { uppercase++; }
else if
(Character.isLowerCase(ch)) { lowercase++; }
else if
(Character.isDigit(ch)) { digits++; }
else if
(Character.isSpaceChar(ch)) { whitespace++; }
else other++;
}
}
fin.close();

System.out.println("Uppercase: " +
uppercase);
System.out.println("Lowercase: " +
lowercase);
System.out.println("Digits: " + digits);
System.out.println("Whitespace: " +
whitespace);
System.out.println("Other: " + other);
}
}
1: Compare outputkeyboard_arrow_up
Output differs. See highlights below.
Input
in1.txt
Your output
Input file: Uppercase: 63 Lowercase: 1969 Digits: 3 Whitespace:
424 Other: 112
Expected output
Input file: Uppercase: 63 Lowercase: 1969 Digits: 3 Whitespace:
478 Other: 112
clear2: Compare
outputkeyboard_arrow_up
Output differs. See highlights below.
Input
in2.txt
Your output
Input file: Uppercase: 11 Lowercase: 917 Digits: 0 Whitespace:
210 Other: 24
Expected output
Input file: Uppercase: 11 Lowercase: 917 Digits: 0 Whitespace:
213 Other: 24
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply