I've been trying to read input from a file and classifying its characters. Printing how many characters are uppercase letters, lowercase letters, digits, white space, and something else in the text file. So I've been working at my code, but I ran into two problems.
When I try to close my scanner I run into a java.lang.IllegalStateException: Scanner closed. Additionally, my code produces an endless loop, but I've been looking at it for hours but I don't know what's wrong. I'm a beginner at Java so I haven't learned about hashmap or Buffered Readers yet. Thank you for all your help.
Here is my code:
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();
Scanner in = new Scanner(new File(inputFileName));
while(in.hasNextLine())
{
String line = in.nextLine();
int len = line.length();
int uppercase = 0 ;
int lowercase = 0;
int digits = 0;
int whitespace = 0;
int other = 0;
for ( int i = 0 ; i < len ; i++)
{
char c = line.charAt(i);
if (Character.isLowerCase(c))
{
lowercase++;
}
else if (Character.isUpperCase(c))
{
uppercase++;
}
else if (Character.isDigit(c))
{
digits++;
}
else if (Character.isWhitespace(c))
{
whitespace++;
}
else
other++;
}
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);
in.close();
}
}
}
You should close Scanner out of the while
loop by using try-with-resouces.
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();
try (Scanner in = new Scanner(new File(inputFileName))) {
while (in.hasNextLine()) {
String line = in.nextLine();
int len = line.length();
int uppercase = 0;
int lowercase = 0;
int digits = 0;
int whitespace = 0;
int other = 0;
for (int i = 0; i < len; i++) {
char c = line.charAt(i);
if (Character.isLowerCase(c)) {
lowercase++;
} else if (Character.isUpperCase(c)) {
uppercase++;
} else if (Character.isDigit(c)) {
digits++;
} else if (Character.isWhitespace(c)) {
whitespace++;
} else
other++;
}
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);
}
}
}
}