newcode
newcode

Reputation: 63

How would I set a string variable and pass it into a File reader scanner as a file name?

I am writing a Cipher program which asks the user for a file name, stores the name as a variable, and is then supposed to read the file based on the String variable. It compiles, but I keep getting an IOException when I try to run it.

 java.io.FileNotFoundException:  (No such file or directory)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.<init>(FileInputStream.java:146)
 at java.io.FileInputStream.<init>(FileInputStream.java:101)
 at java.io.FileReader.<init>(FileReader.java:58)
 at Cipher.main(Cipher.java:22)

I don't understand what is happening. It gives the error before the user has a change to type the file name. Here is my code:

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

public class Cipher {

public static void main (String [] args) throws FileNotFoundException {

        String inFile = "";

        Scanner sc = new Scanner (System.in);
            System.out.println("Welcome to Caeser Cipher");
            System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit): ");
            int cipher = sc.nextInt();

        System.out.println("What non-negative shift should I use?");
            int shift = sc.nextInt();

            System.out.println("What is the input file name?");
            inFile = sc.nextLine();
            try {

                Scanner input = new Scanner (new FileReader (inFile) ) ;
                String line = input.nextLine();



       /* System.out.println("What is the output file name?");
         String outFile = sc.nextLine();*/

        Scanner input = new Scanner (new FileReader (inFile) ) ;
        input.useDelimiter("['.!?0-9+");

        String line = input.nextLine();

        while (input.hasNextLine()) {

                line = input.nextLine();

                if (cipher == 1) {
                    System.out.println(caeserEncipher(line, shift));
                } else if (cipher == 2) {
                    System.out.println(caeserDecipher(line, shift));
                } else {
                    System.out.println ("Enter 1 to encipher, or 2 to decipher (-1 to exit)");
                    return;
                }
            }
        }

        catch (FileNotFoundException e) {
            System.out.println ("Trouble opening or reading the file...");
            System.out.println ("Perhaps it was misspelled!");
            e.printStackTrace();
        }
    }

   public static String caeserEncipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] += shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char)arr[i]);
        }

        output = builder.toString();
        return output;

}

public static String caeserDecipher(String input, int shift) {
int arr[] = new int[input.length()];
StringBuilder builder = new StringBuilder();
int length = input.length();
String output = "";

for (int i = 0; i < length; i++) {
    arr[i] = (int) input.charAt(i);
    arr[i] -= shift;
}

for (int i = 0; i < length; i++) {
    builder.append((char)arr[i]);
}

output = builder.toString();
return output;

    }

}

Upvotes: 0

Views: 579

Answers (2)

Ashishkumar Singh
Ashishkumar Singh

Reputation: 3600

Issue with your code

you are directly calling scanner.nextLine() after scanner.nextInt() is called .

In this scenario if you input say 5 for nextInt() and press enter, then it would return 5 forscanner.nextInt()andnew lineforscanner.nextLine(). This occurs becausescanner.nextInt()doesn't consume the last newline leading tonextLinehavingnewline. So, in your case, user will not get a chance to input the file-name leading to error and it would seem thatscanner.nextLine()` call is skipped.

So before calling scanner.nextLine(), add another scanner.nextLine() above it just to consume the last new line.

As far as the file name is concerned, run your program with absolute path and it should run fine: like D:\Work\file.txt

Upvotes: 1

anoopknr
anoopknr

Reputation: 3355

Your code has many mistakes.

  1. Multiple time declaration of input,line.
  2. wrong regular expression. "['.!?0-9+" should be "\\['.!?0-9+".
  3. Un managed newline (Enter) after scanner.nextLine() .

Try this modified code :-

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

public class Cipher {

    public static void main(String[] args) throws FileNotFoundException {

        String inFile = "";

        // avoiding multtiple delcaration.
        Scanner input = null;
        String line = "";

        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to Caeser Cipher");
        System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit): ");
        int cipher = sc.nextInt();

        System.out.println("What non-negative shift should I use?");
        int shift = sc.nextInt();

        sc.nextLine(); // clearing '\n' (newline)
        System.out.println("What is the input file name?");
        inFile = sc.nextLine();
        try {

            input = new Scanner(new FileReader(inFile));
            line = input.nextLine();

            /*
             * System.out.println("What is the output file name?"); String outFile =
             * sc.nextLine();
             */

            input = new Scanner(new FileReader(inFile));
            input.useDelimiter("\\['.!?0-9+");            // changed reg-expression

            line = input.nextLine();

            while (input.hasNextLine()) {

                line = input.nextLine();

                if (cipher == 1) {
                    System.out.println(caeserEncipher(line, shift));
                } else if (cipher == 2) {
                    System.out.println(caeserDecipher(line, shift));
                } else {
                    System.out.println("Enter 1 to encipher, or 2 to decipher (-1 to exit)");
                    return;
                }
            }
        }

        catch (FileNotFoundException e) {
            System.out.println("Trouble opening or reading the file...");
            System.out.println("Perhaps it was misspelled!");
            e.printStackTrace();
        }
    }

    public static String caeserEncipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] += shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char) arr[i]);
        }

        output = builder.toString();
        return output;

    }

    public static String caeserDecipher(String input, int shift) {
        int arr[] = new int[input.length()];
        StringBuilder builder = new StringBuilder();
        int length = input.length();
        String output = "";

        for (int i = 0; i < length; i++) {
            arr[i] = (int) input.charAt(i);
            arr[i] -= shift;
        }

        for (int i = 0; i < length; i++) {
            builder.append((char) arr[i]);
        }

        output = builder.toString();
        return output;

    }

}

Upvotes: 0

Related Questions