import java.nio.file.*;
import java.io.*;
public class Hw3pr2 {
public static void main(String[] args) throws IOException {
String f = "Hw3pr2.java";
char c = 'a';
FileInputStream fis = new FileInputStream(f);
int count=0;
int r;
while ((r = fis.read()) != -1) {
if (c == (char)r){
count = count + 1;
}
}
System.out.println("Total: " + count);
}
}
You need to use a loop:
for (int i=0; i
The assignment is:
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file.
import java.util.Scanner;
import java.io.*;
public class Hw3pr2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//get the file name
System.out.println("Enter the name of a file.");
String fileName = keyboard.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//get the character
System.out.println("Enter any character.");
String letterInput = keyboard.nextLine();
char letter = letterInput.charAt(0);
and that's where I'm stuck. I know I can read lines in the file using inputFile.nextLine(); but how can I read individual characters?
Any help would be appreciated! Thanks!