Why does this program terminate when I enter user input? - java

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");
}
}
}

Related

Trying two Link classes with Java

I am trying to link two files together and have one count the amount of characters and have the other one give the answer to the character counter. The first file cant have the word that is being given to be displayed as well. How would I go about doing so?
File one
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
System.out.println("Line " + (answer + 1));
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The specific Line is: " + text);
}
File two
public class countWords
{
public static void main(String[] args) {
String string = "nose";
int count = 0;
//Counts each character except space
string = string.replaceAll(" ", "");
count = string.length();
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Figured it out for the first file
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
WordCounter wc = new WordCounter(text);
wc.removeSpaces();
wc.count();
int letters = wc.getCount();
System.out.println("The amount of characters is:" + letters);
}
}
Got the second file
public class WordCounter
{
private final String word;
private int count = 0;
public WordCounter(String word) {
this.word = word;
}
public void removeSpaces() {
word.replaceAll(" ", "");
}
public void count() {
count = word.length();
}
public int getCount() {
return count;
}
}

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();
}
}

Character Count

I'm trying to count the number of Words, Lines and characters(excluding whitespace). The only part I can't get to work is ignoring the whitespace for the character count.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args) throws IOException{
File file = getValidFile();
int count = wordCount(file);
int lines = lineCount(file);
int characters = characterCount(file);
System.out.println("Total Words = " + count);
System.out.println("Total Lines = " + lines);
System.out.println("Total Characters = " + characters);
}
public static int characterCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file).useDelimiter(",\\s*");;
int characters = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
characters++; //count the word
}
inputFile.close();
return characters;
}
}
public static int lineCount(File file)throws IOException {
{
Scanner inputFile = new Scanner(file);
int lines = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.nextLine(); //read in a line
lines++; //count the line
}
inputFile.close();
return lines;
}
}
public static int wordCount(File file) throws IOException {
{
Scanner inputFile = new Scanner(file);
int count = 0; // initialise the counter variable
while (inputFile.hasNext())
{
inputFile.next(); //read in a word
count++; //count the word
}
inputFile.close();
return count;
}
}
public static File getValidFile()
{
String filename; // The name of the file
File file;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get a valid file name.
do
{
/*for (int i = 0; i < 2; i ++ )
{*/
System.out.print("Enter the name of a file: ");
filename = keyboard.nextLine();
file = new File(filename);
if (!file.exists())
System.out.println("The specifed file does not exist - please try again!");
}while( !file.exists());
return file;
}
}
If you want to count the characters in the file, excluding any whitespace, you can read your file line by line and accumulate the character count, or read the whole file in a String and do the character count, e.g.
String content = new Scanner(file).useDelimiter("\\Z").next();
int count = 0;
for (int i = 0; i < content.length(); i++) {
if (!Character.isWhitespace(content.charAt(i))) {
count++;
}
}
System.out.println(count);
EDIT
Other solutions if you don't care about the content of the file, then there is no need to load it into a String, you can just read character by character.
Example counting the non-whitespace characters in Arthur Rimbaud poetry.
Using a Scanner
URL rimbaud = new URL("http://www.gutenberg.org/cache/epub/29302/pg29302.txt");
int count = 0;
try (BufferedReader in = new BufferedReader(new InputStreamReader(rimbaud.openStream()))) {
int c;
while ((c = in.read()) != -1) {
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);
Using a plain StreamReader
count = 0;
try (Scanner sin = new Scanner(new BufferedReader(new InputStreamReader(rimbaud.openStream())))) {
sin.useDelimiter("");
char c;
while (sin.hasNext()) {
c = sin.next().charAt(0);
if (!Character.isWhitespace(c)) {
count++;
}
}
}
System.out.println(count);

Parse a file into an array and then search for words in the file, count the words in the file

I can parse the file and I can read out the contents of the file, but I am unable to search for a specific word in the file or count the number of words in the file:
Code below:
public class Manager{
private String[] textData;
private String path;
public String loadFile (String file_path){
return path= file_path;
}
public String [] openFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader (file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine =bf.readLine()) !=null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
private int findText(String s){
for (int i = 0; i < textData.length; i++){
if (textData[i] != null && textData[i].equals(s)){
return i;
}
}
return -1;
}
public boolean contains(String s){
for(int i=0; i<textData.length; i++){
if(textData[i] !=null && textData[i].equals(s)){
return true;
}
}
return false;
}
public int count(){
int counter = 0;
for (int i = 0; i < textData.length; i++){
if (textData[i] != null) counter++;
}
return counter;
}
}
My other Class:
ublic class Runner {
private String fileInput;
private Scanner scanner = new Scanner(System.in);
private boolean keepRunning= true;
private Manager m = new Manager();
public static void main(String[] args) throws Exception {
new Runner();
}
public Runner() throws Exception{
do {
System.out.println("--------------------------------------------------");
System.out.println("\t\t\t\tText Analyser");
System.out.println("--------------------------------------------------");
System.out.println("1)Parse a File");
System.out.println("2)Parse a URL");
System.out.println("3)Exit");
System.out.println("Select option [1-3]>");
String option = scanner.next();
if (option.equals("1")){
parseFile();
}else if(option.equals("2")){
parseUrl();
}else if(option.equals("3")){
keepRunning = false;
}else{
System.out.println("Please enter option 1-3!");
}
} while (keepRunning);
System.out.println("Bye!");
scanner.close();
}
private void parseFile()throws Exception{
String file_name;
System.out.print("What is the full file path name of the file you would like to parse?\n>>"); ////The user might enter in a path name like: "C:/Users/Freddy/Desktop/catDog.txt";
file_name = scanner.next();
try {
Manager file = new Manager();
file.loadFile(file_name);
String[] aryLines = file.openFile( );
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch ( IOException e ) {
System.out.println( e.getMessage() );
}
do {
System.out.println("*** Parse a file or URL ***");
System.out.println("1)Search File");
System.out.println("2)Print Stats about File");
System.out.println("3)Exit");
System.out.println("Select option [1-3]>");
String option = scanner.next();
if (option.equals("1")){
}else if(option.equals("2")){
}else if(option.equals("3")){
keepRunning = false;
}else{
System.out.println("Please enter option 1-3!");
}
} while (keepRunning);
System.out.println("Bye!");
scanner.close();
}
private void parseUrl()throws Exception{
}
private void search() throws Exception{
do {
System.out.println("*** Search ***");
System.out.println("1)Does the file/URL contain a certain word");
System.out.println("2)Count all words in the file/url");
System.out.println("9)Exit");
System.out.println("Select option [1-9]>");
String choice = scanner.next(); //Get the selected item
if (choice.equals("1")){
contains();
}else if(choice.equals("2")){
count();
}else if(choice.equals("3")){
keepRunning = false;
}else{
System.out.println("Please enter option 1-3!");
}
} while (keepRunning);
System.out.println("Bye!");
scanner.close();
}
private void contains(){
System.out.println("*** Check to see if a certain Word/Letter appears in the file/URL ***");
System.out.println("Enter what you would like to search for:");
String s = scanner.next();
boolean sc = m.contains(s);
System.out.println("If its true its in the file, if its false its not in the file/URL");
System.out.println("The answer = " + sc);
}
private void count(){
int totalNumberOfElement = m.count();
System.out.println("Total number of elements in the file/Url is" + totalNumberOfElement );
}
Consider the below points to change your code:
1. Use a List (eg: List contents = new List) for reading the lines from a file
2. Use contents.size() to get the number of lines. That would be simple.
3. You are using equals() method to search for text in a line. Use contains() or indexOf() methods. Better, use regex if you are aware of it.
I think the easyest way is something like the following:
public boolean contains(String s){
return textData.toLowerCase().contains(s.toLowerCase())
}
but that only is goint go work for strings!
I've written some code below. See whether it helps you. Please don't copy-paste, try to learn the logic also.
import java.io.*;
public class Manager
{
String[] textData;
String path;
int numberOfWords;
public void loadFile(String path) throws Exception
{
this.path = path;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(path));
String line;
String[] words;
numberOfWords = 0;
while((line=reader.readLine()) != null)
{
buffer.append(line + "\n");
words = line.split(" ");
numberOfWords = numberOfWords + words.length;
}
//deleting the last extra newline character
buffer.deleteCharAt(buffer.lastIndexOf("\n"));
textData = buffer.toString().split("\n");
}
public void printFile()
{
for(int i=0;i<textData.length;i++)
System.out.println(textData[i]);
}
public int findText(String text)
{
for(int i=0;i<textData.length;i++)
if(textData[i].contains(text))
return i;
return -1;
}
public boolean contains(String text)
{
for(int i=0;i<textData.length;i++)
if(textData[i].contains(text))
return true;
return false;
}
public int getNumberOfWords()
{
return numberOfWords;
}
public int getCount()
{
return textData.length;
}
}

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