i'm trying to create a program that asks the user to input a file (but the file name is standard name that will not change) and input a specific character. The program will use looping to find how many of that specific character is in the .txt file. This is the coding I have and an error message comes up after the user input prompts come up.

import java.util.Scanner;
import java.io.*;

public class Assn3Prog1
{
public static void main(String[] args) throws IOException
{

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a filename: ");
String filename = keyboard.nextLine();


System.out.print("Enter a character: ");
String character = keyboard.nextLine();
char answerChar = Character.toLowerCase(character.charAt(0));

File file = new File("File.txt");
Scanner inputFile = new Scanner(file);

long max = file.length();
int numCharacters = 0;

character = inputFile.nextLine();



for (int i = 0; i < max; ++i)
    {char randomChar = Character.toLowerCase(filename.charAt(i));
    if (answerChar == randomChar)
    ++numCharacters;}


System.out.println("Found " + numCharacters +  " of those characters in the file.");


inputFile.close();


}}

Recommended Answers

All 3 Replies

error message comes up after the user input prompts come up.

Could you post that error message here

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
at java.lang.String.charAt(String.java:686)
at Assn3Prog1.main(Assn3Prog1.java:36)

why are you asking for a filename, if you are going to use a hardcoded one?
also: you are reading the charAt from the filename your user entered, not from the file you're working with.

your max is based on the length of the contents of File1.txt, but you are searching the filename you entered. if that is shorter than the lengt of the contents of File1.txt, you'll automatically get that error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.