Reading file line by line and print - java

I'm trying to write a program that takes the file name from the user (for example: English), then opens this file and prints (9 questions) divided on (3 levels, each level has 3 questions), then opens another file (EnglishC) that contains the answers and then compares it with the correct answer. if correct grade++.
Output:
enter your choice:
1.English
2.Math
3.Science
java.io.FileNotFoundException: English.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at Generater.createQuestions(Generater.java:50)
at Generater.choose_subject_And_Level(Generater.java:41)
at Generater.main(Generater.java:139)
Source:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Generater {
static int levelNo = 1;
static int subjectName;
static int grade;
static String fileName;
static String fileNameCorrect;
static String ans;
static String correctAns;
public static void choose_subject_And_Level() {
// here the main will call this method to ask the user what subject to be tested in?
Scanner input = new Scanner(System.in);
System.out.println("enter your choice:\n 1.English\n2.Math\n3.Science ");
subjectName = input.nextInt();
switch (subjectName) {
case 1:
fileName = "English.txt";
fileNameCorrect = "EnglishC.txt";
break;
case 2:
fileName = "Math.txt";
fileNameCorrect = "MathC.txt";
break;
case 3:
fileName = "Science.txt";
fileNameCorrect = "SienceC.txt";
break;
}
createQuestions(fileName, fileNameCorrect, levelNo);
}
public static void createQuestions(String fileName, String fileNameCorrect,
int levelNo) {
Scanner input, input2;
try {
input = new Scanner(new File(fileName));
input2 = new Scanner(new File(fileNameCorrect));
input.useDelimiter("*");
FileInputStream fs = new FileInputStream(fileName);
FileInputStream fs2 = new FileInputStream(fileNameCorrect);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));!
while (input.hasNext()) {
switch (levelNo) {
case 1:
for (int i = 1,k=1; i <= 3 ; i++,k++) {
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 2:
for (int i = 4, k = 1; i <= 6; i++, k++) {
try {
for (int j = 1; j <= 3; j++) {
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 3:
for (int i = 7, k = 1; i <= 9; i++, k++) {
try {
for (int j = 1; j <= 6 ; j++){
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// the main
public static void main(String[] args) {
choose_subject_And_Level();
}
}

When java.io.FileNotFoundException is thrown it means the file that is supposed to be read/written is not present at the location specified. Look where you have the file on the filesystem and confirm that the file in question (English.txt) is present.
More info here: https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

Related

Why my Java program works perfectly in windows but it's a disaster in linux?

I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}

I'm getting FileNotFound exception while trying to create a file

I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}

Why does this program terminate when I enter user input?

The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}

Scanner will take user input but will not find the file

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

making a line of text from a text file into a cipher text in java

I have a line of text that I need to decrypt into a cipher text.
Let's say my line of text is abc def ghijklm n opq rstu vwx yz
and I want an output like this: aei qu c k rvzdhmptxbfjn y glosm
lets say I entered my "key" as 5. The code then will enter every 5th element of the array o f strings of the text from the text file.
This is the code I have come up with and I have hit a wall on what to do.
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
char arrayText[] = text.toCharArray();
for (int i = 0; i < arrayText.length; i += key) {
System.out.print("\n" + arrayText[i]);
}
}
}
}
Here is whats happening in the console:
Enter file: abc.txt
File name is: abc.txt
abc def ghijklm n opq rstu vwx yz
a
e
i
q
u
What you need is a circular list.
Here is a very simple and crude implementation of a circular list using arrays.
import java.util.Iterator;
import java.util.List;
public class CircularList implements Iterator<String> {
private String[] list;
private int pointerIndex;
private int key;
public CircularList(String[] list, int key) {
this.list = list;
pointerIndex = 1 - key;
this.key = key;
}
#Override
public boolean hasNext() {
if(list.length == 0){
return false;
}
return true;
}
#Override
public String next() {
if(pointerIndex + key > list.length) {
int diff = (list.length-1) - pointerIndex;
pointerIndex = key - diff;
return list[pointerIndex];
}else {
pointerIndex = pointerIndex + key;
return list[pointerIndex];
}
}
#Override
public void remove() {
//Do Nothing
}
}
Once you have a list in which you can iterate in a circular fashion, you can change you existing implementation to this -
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
System.out.print("Enter file: ");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
Scanner inputStream = null;
System.out.println("" + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file: " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
String[] splits = text.split("");
CircularList clist = new CircularList(splits, 5);
for (int i = 0; i < splits.length -1; i += 1) {
System.out.print("" + clist.next());
}
}
}
}
Output -
Enter file: resources\abc.txt
resources\abc.txt
abc def ghijklm n opq rstu vwx yz
aei qu c k rvzdhmptxbfjn y glosw
Also the last character in your cipher should be 'w' and not 'm'.
You don't specify what should happen to the spaces, or what happens when wraparound is required, but assuming spaces are significant and wrap-around just happens naturally:
for (int i = 0; i < text.length(); i++)
{
System.out.print(text.charAt((i*5) % text.length()));
}
prints aei qu c k rvzdhmptxbfjn y glosw, which strongly suggests an error in your expected output.
import java.io.;
import java.util.;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
for (int i = 0; i < text.length(); i++) {
System.out.print(text.charAt((i * key) % text.length()));
}
}
}
}
MANY THANKS TO EJP AND Pai!
i learned alot!

Categories

Resources