search program in txt file java code - java

I wanna develop java program with following task.
use enter file name and also enter product code. and as result its show all products details
for example.
file data is MLK#milk#expired date 15 may 2016
output will be
this product name is milk with MLK code and will expired in 15 may 2016.
help me thanks...
my code is...
import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
while(file.hasNextLine())
{
String data=file.nextLine();
System.out.println(data);
}
//System.out.println("");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Station does not exist");
break;
}
}
}
}

package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String tokens[] = null;
String code, product, date;
try {
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
tokens = line.split("#");
code = tokens[0];
product = tokens[1];
date = tokens[2];
System.out.println("this product name is " + product
+ " with " + code
+ " code and will expired in"
+ date.substring(12));
line = br.readLine();
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found exception.");
} catch (IOException e) {
System.out.println("IO Eception occered.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
//split the string on # character so that you get code, product name and expiration date separately.
String arr[] = line.split("#");
//check whether the string contains the required string or not
try{
if(arr[0].equalsIgnoreCase(word) || arr[1].equalsIgnoreCase(word)){
//line break
System.out.println();
//split the format 'expiration date 15 may 2016' so that we can use date separately without the heading of 'expiration date'
String dateStrings[] = arr[2].split(" ");
System.out.print("this product name is " + arr[1] + " with " + arr[0] + " code and will expire on ");
System.out.println(dateStrings[2] + " " + dateStrings[3] + " " + dateStrings[4]);
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
catch(IndexOutOfBoundsException indexEx){
val = 0;
continue;
}
}
if(val == 0){
System.out.println("Station does not exist");
break;
}
}
}
}
The above code will search the string that will be read from the file if it contains the word to search or not. It can be product code or product name

Related

How to get class variable file check to print line rather than throw exception

I'm trying to get a method to check for the existence of a file, and print a message that the file doesn't exist, but it also has to be a class variable rather than an instance variable.
I had it working when it was only in subString method, was not a class variable and without infix/suffix/prefix code.
Here is my code. It's still a little bit messy and no conforming to formatting convention.
Appreciate your help.
package wordgames;
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class WordGames {
private static final String DICTIONARY = "dictionary.txt";
private static String[] wordsCollection;
private static int wordCount = 0;
public static void main(String[] args) throws Exception {
wordsCollection = new String[100];
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
getSelection();
}
static String getSelection() throws FileNotFoundException {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selections: ");
String selection = keyboardInput.next();
switch (selection) {
case "1":
subStringProblem();
case "2":
pointsProblem();
case "3":
System.out.println("Good Bye!");
System.exit(0);
default:
System.out.println("Invalid option. Try again.");
getSelection();
}
return null;
}
static void subStringProblem() throws FileNotFoundException {
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
} else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
System.out.println("Substring problem.");
System.out.println("Enter a Substring:");
Scanner keyboardInput = new Scanner(System.in);
String subString = keyboardInput.next();
System.out.print(subString);
System.out.println();
String notFound = " - not found";
String infixFound = " - infix";
String prefixFound = " - prefix";
String suffixFound = " - suffix";
for (int i = 0; i < wordCount; i++) {
String temp = wordsCollection[i];
boolean found = false;
if (wordsCollection[i].startsWith(subString)) {
found = true;
temp = temp + prefixFound;
}
if (wordsCollection[i].endsWith(subString)) {
found = true;
temp = temp + suffixFound;
}
if (wordsCollection[i].contains(subString)) {
found = true;
temp = temp + infixFound;
}
if (!found) {
System.out.printf(" " + wordsCollection[i] + notFound + "\n");
} else {
System.out.printf(" " + temp + "\n");
}
}
getSelection();
}
private static void pointsProblem() throws FileNotFoundException {
System.out.println("Points problem.");
getSelection();
}
}
I've noticed that you have put throws FileNotFoundException in the signature of all of your functions. You only do this if you don't want to catch the exception in that function, and want the caller to be responsible for handling the exception. In your program, that is never the case, you always want to handle it immediately by exiting, so remove it from everywhere.
The part of your code that is crashing:
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
This code will work if you remove the fileScanner. It throws an exception if the file doesn't exist, but since you're not actually using it for anything, you can just remove it. The fileReader.isFile() check will then do the job. (fileReader.exists() is closer to)
The corrected code:
File fileReader = new File("DICTIONARY.txt");
if (fileReader.exists() == false) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
You're also reading a file in the main() function. There you're actually using the fileScanner, so this gives you a choice of either using the same check as above, or you can actually catch the FileNotFoundException this time, you could try that at least to give it a try.
try {
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
} catch (FileNotFoundException e) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
It would be good practice if within the try/catch block you actually called a function, that would make stop it from looking ugly.

java.lang.ArrayIndexOutOfBoundsException and If entry after the comma is not an integer

I keep getting the error: java.lang.ArrayIndexOutOfBoundsException: 1 within my code. This is my first semester learning java so any help would be greatly appreciated. Also, to kill two birds with one stone. I'm having problems with one of my if statements.
If entry after the comma is not an integer:
Output: "Error: Comma not followed by an integer."
Thanks in advance.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.StringWriter;
public class DataVisualizer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner inSS = null;
String title = "";
String column1header = "";
String column2header = "";
String dataString = "";
String dataPoint = "";
String dataInt = "";
boolean inputDone = false;
char comma = ',';
System.out.println("Enter a title for the data: ");
title = input.nextLine();
System.out.println("You entered: " + title);
System.out.println("");
System.out.println("Enter the column 1 header: ");
column1header = input.nextLine();
System.out.println("You entered: " + column1header);
System.out.println("");
System.out.println("Enter the column 2 header: ");
column2header = input.nextLine();
System.out.println("You entered: " + column2header);
System.out.println("");
ArrayList<String> string = new ArrayList<String>();
ArrayList<Integer> integer = new ArrayList<Integer>();
System.out.println("Enter a data point (-1 to stop input): ");
while (!inputDone) {
dataPoint = input.nextLine();
inSS = new Scanner(dataPoint);
if (dataPoint.equals("-1")) {
inputDone = true;
break;
}
if (!dataPoint.contains(",")) {
System.out.println("Error: No comma in string.");
}
// Here is the problem I am running with my if statement.
if (dataPoint.indexOf(",") != dataPoint.lastIndexOf(",")) {
System.out.println("Error: Too many commas in input.");
}
if (Character.isDigit(dataPoint.charAt(-1))) {
System.out.println("Error: Comma not followed by an integer.");
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");
}
else {
// This is where Im getting my error
String[] items = dataPoint.split(",");
for (int i = 0; i < items.length; ++i){
dataString = items[0];
dataInt = items[1];
}
Integer dataInteger = Integer.valueOf(dataInt);
System.out.println("Data string: " + dataString);
System.out.println("Data integer: " + dataInteger);
string.add(dataString);
integer.add(dataInteger);
}
System.out.println("");
System.out.println("Enter a data point (-1 to stop input): ");
}
return;
}
}
You're trying to get the char at index -1, here you will be getting StringIndexOutOfBoundsException
Character.isDigit(dataPoint.charAt(-1))
The index should be between 0 to string.length()-1

Why isn't my file being opened?

The file is in the root directory of where my source code is. Also is having a number appened to the end of the path variable going to mess things up or how would you do that?
There are 10 files to choose from and they all have similar names but end with a different number. So I was thinking of having the default path variable and then append the number to it and then doing File nameFile = new File(path + year + ".txt")
Any idea why it's not picking it up?
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class nameRanker {
public static void main(String[] args) throws Exception {
int skip = 0;
int rank = 0;
int year = 0;
char gender = '0';
String name = "";
String compareName = "";
Boolean found = false;
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: "); //try to catch mismatched input here (0-10)
try { year = input.nextInt();
System.out.print("\nEnter the gender: "); //try to catch mismatched input here (M or F)
gender = input.next().charAt(0);
System.out.print("\nEnter the name: "); //try to catch mismatched input here (no #)
name = input.next();
}
catch (InputMismatchException e) {
e.printStackTrace();
System.err.println("Entered value does not match expected value. \n(Year must be integer, gender M or F, and name must be a string.)");
}
String path = "\\BabynamesrankingFiles\\Babynamesranking";
File nameFile = new File(path + year + ".txt"); //throws IOexception if not found
//Scanner readFile = null;
try (Scanner readFile = new Scanner(nameFile)){
//readFile = new Scanner(nameFile);
if(nameFile.canRead()){ //if the file is readable
while(readFile.hasNext() && !found){ //while data in file
if(gender == 'M'){ //if male only parse first two values
rank = readFile.nextInt(); //store rank
compareName = readFile.next(); //grab name to compare
found = (compareName == name) ? true : false; //if name found break while loop
}
if(gender == 'F'){
rank = readFile.nextInt(); //store the rank
compareName = readFile.next(); //store the boy name
skip = readFile.nextInt(); //store the total names value even though unused
compareName = readFile.next(); //store the girl name to compare
found = (compareName == name) ? true : false; //if name found break while loop
}
} //end while loop
if(!found){ //if name not found
System.out.println("The name " + name + "is not ranked in year " + year);
}
else{
System.out.println("The name " + name + " is ranked " + rank + " in the year " + year);
}
}
}
catch(IOException ex){
System.out.println("Error could not open file, check file path.");
}
finally {
input.close(); //close scanner
}
}
}

How would I modify this so that rather than have it break it will just request the user to enter the file name again?

The problem
When the user enters the filename into the program, it will create an exception stating that there is no file named like that in the directory.
What I want is that - instead of showing an exception - the program will repeat the message that asks the user to enter the filename.
My code:
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName);
}else{
}
}
}
private static void processFile(String fileName) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
You can try determine if the file exists first by doing something like the following:
File file = new File(fileName);
if(file.exists()) {
processFile(fileName)
}
Here is the solution
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
File file = new File(fileName);
if(!file.exists()) {
continue;
}
processFile(fileName);
}
}
Use this code:
String fileName;
File file;
for(;;) {
/* read file name */
System.out.print("enter file name: ");
fileName = bufferedReader.readLine();
file = new File(fileName);
/* check path */
if (!file.exists())
System.out.println("file doesn't exist");
else if(!file.isFile())
System.out.println("file isn't a regular file");
else if (...)
...
else
break;
}
where bufferedReader is BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); if you want to read file name from keyboard.
You can check if file exists exists(), is a regular file isFile(), is a directory isDirectory(), can be read carRead(), wrote canWrite(), executed canExecute(), an so on..

Outputting to a closed stream?

So I fixed my program but the problem is that after replacing all the blank spaces with tildes i have to output the text to a file that has been closed. How would I re-open the file for output and input something in?
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next() /* ("\\S+") */;
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
}
}
System.out.println();
System.out.println("There are " + numOfVowelsA
+ " A vowels in this file of text");
System.out.println("There are " + numOfVowelsE
+ " E vowels in this file of text.");
System.out.println("There are " + numOfVowelsI
+ " I vowels in this file of text.");
System.out.println("There are " + numOfVowelsO
+ " O vowels in this file of text.");
System.out.println("There are " + numOfVowelsU
+ " U vowels in this file of text. ");
Scanner tildes = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
while (tildes.hasNext()) {
String replace = tildes.nextLine();
replace = replace.replaceAll(" ", "~");
System.out.println();
System.out.print(replace);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}
You didn't close inFile. Close inFile first and then you are able to open it again in tildes.
Close it before Scanner tildes = new Scanner(...); line.

Categories

Resources