Use boolean to search duplicate - java

I want to use boolean to search duplicate when I need to print out a list of names. So I need to write a program to read names in a text file and print it out to console. But the compiler doesn't work in this case. I don't know why? Can you guys help me?
import java.io.*;
import java.util.*;
public class NameSorter
{
public static void main(String[] args) throws Exception
{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to sort names stored in a file.");
System.out.println();
//Get input
String fileName;
System.out.print("Enter the file's name: ");
fileName = cin.readLine();
fin = new BufferedReader(new FileReader(fileName));
int nNames = 0;
String[] name = new String[8];
//initialize array elements
for(int i=0; i<name.length;i++)
{
name[i]=" ";
}
// read text file
while(fin.ready())
{
String aName = fin.readLine();
String temp = aName;
boolean check;
if(temp.compareTo(" ")>0)
{
for(int i=0; i<name.length;i++)
{
if(temp.compareToIgnoreCase(name[i])==0)
{
check = true;
break;
}
}
}
if(nNames<name.length&& check = false)
{
name[nNames++] = temp;
}
}
}
fin.close();
// Sort the names aphabetically.
for(int i=0;i<nNames; i++)
{
int j;
for(j=i+1;j<nNames; j++)
{
if(name[i].compareToIgnoreCase(name[j])>0)
{
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for(int i=0; i<name.length;i++)
System.out.println(name[i]);
}
}

Your code is :
if(nNames<name.length && check = false)
check= false , assigns false to check. To compare check with false you can use
check==falseor !check.
Depending on what you are trying to validate. The below code will remove the compilation error:
check == false //checks if check is false
Or,
if(nNames<name.length && (check = false))
// above is same as if(nNames<name.length && false) // which will always be false

Related

Accessing indexes that may not exist Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code

how can i read and store reattempts?

public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
on hover over component 1 change the style
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadTemps{
public static void main(String[] args) throws IOException {
//taking the word to search from keyboard
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the word you want to search: ");
String input = keyboard.nextLine();
//counter for calculating how many times word wrote in line
int counter = 0;
//counter to find which line we are searching
int counterLine = 1;
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("C:\\KeyWestTemp.txt"));
// Original answer used LinkedList, but probably preferable to use
// ArrayList in most cases
// List<String> temps = new LinkedList<String>();
ArrayList<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.nextLine();
//removing whitespeaces
token1.replaceAll("\\s+","");
//taking all the letters as String
for(int i = 0; i < token1.length(); i++) {
char c = token1.charAt(i);
String s = "" + c;
temps.add(s);
}
//adding a point to find line' end
temps.add("line");
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
//searching on array to find first letter of word
for (int i = 0; i < tempsArray.length; i++) {
String s = temps.get(i);
//if its the end of line time to print
if(s.equals("line")) {
System.out.println("Line" + counterLine + " : " + counter + " occurrence ");
counterLine++;
counter = 0;
}
//if the first letter found need to search rest of the letters
if(s.equalsIgnoreCase("" + input.charAt(0))) {
s = "";
try {
for(int j = i; j < i + input.length(); j++) {
String comp = temps.get(j);
if(comp.equalsIgnoreCase("" + input.charAt(j-i)))
s = s + comp;
}
} catch (IndexOutOfBoundsException e) {
}
//checks if found the word
if(s.equalsIgnoreCase(input))
counter++;
}
}
}
}
This is the code i got for searching char by char for wanted String.
Rather than using inFile1.next();, use inFile1.nextLine(), and don't bother wasting time using a token string.
while (inFile1.hasNext()) {
temps.add(inFile1.nextLine());
}
use BUFFERED READER , it read line by line
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String fullLine;
while ((line = br.readLine()) != null) {
}
}

Array Index out of bounds for Java using terminal

I am having trouble with a ticketing system that I am trying to create using java. I am trying to utilize two files to read and write my inputs. I am testing with just salesSell method at the moment. I am passing the args using terminal. The problem that I am having is an arrayoutofbounds exception that gets thrown.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cisc_327_frontend.Frontend_try1.main(Frontend_try1.java:763)
the two array parameters that I am passing are parsed from the same line in my current events file. an example of a line in the file is : "testevent1__________0003". I cannot seem to figure out where I am having this problem. Any type of guidance would be much appreciated.
package cisc_327_frontend;
import java.io.*;
import java.util.*;
public class Frontend_try1 {
private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();
public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
System.out.println("Enter command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true;
do{
if(inputString.toUpperCase().equals( "LOGIN")) {
//enter login mode
login(namesArray, ticketArray,fileCurrentEvents);
correct = true;
}
if(inputString.toUpperCase().equals("LOGOUT")){
logout(namesArray, ticketArray,fileCurrentEvents);
correct=true;
}
if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
System.out.println("Incorrect command, please enter command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
System.out.println("Sales or Admin?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout(null, null, null);
}
else if(inputString.toUpperCase().equals("SALES")) {
//enter sales mode
sales(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("ADMIN")) {
//enter admin mode
admin(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Sales or Admin?");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
//System.out.println("SALES");
System.out.println("Sales Mode");
System.out.println("Enter Command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
else if(inputString.toUpperCase().equals("SELL")) {
//enter sales Sell mode
salesSell(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("RETURN")) {
//enter sales Return mode
salesReturn(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter Logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Enter Command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
int index = 0;
String eventName = null;
int numberTickets = 0;
System.out.println("Sales Sell Mode");
System.out.println("What is the name of your event?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
try{
for(int i = 0; i < namesArray.length; i++) {
if(namesArray[i].equals(inputString)){
index = i;
}
}
eventName= namesArray[index];
numberTickets=ticketArray[index] ;
} catch (Exception e) {
System.out.println("Error: Event not found within file");
System.exit(1);
}
int event = inputString.length();
boolean charnumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(event< 0 || event >20){
System.out.println("No more than 20 characters allowed for name!");
System.out.println("Enter name:");
input = new Scanner(System.in);
inputString = input.nextLine();
event=inputString.length();
charnumber = false;
}
else{
charnumber = true;
}
} while(!charnumber);
System.out.println("How many tickets?");
input = new Scanner(System.in);
inputString = input.nextLine();
int digit;
while(true){
try {
digit = Integer.parseInt(inputString);
break;
}
catch(NumberFormatException e){
}
System.out.println("Please type a number!");
inputString = input.nextLine();
}
if( numberTickets - digit <0){
System.out.println("Illegal amount of tickets! Buy less ticket please.");
}
else{
int tickets = numberTickets - digit;
ticketArray[index]=tickets;
}
boolean dignumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(digit<0 || digit>8){
System.out.println("Only 8 tickets allowed to be sold!");
inputString = input.nextLine();
event=inputString.length();
dignumber = false;
digit= Integer.parseInt(inputString);
}
else{
dignumber= true;
}
}while(!dignumber);
}
public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
FileWriter logoutFileWriter;
FileWriter currEventsFileWriter;
int numSpaces = 0;
try{
currEventsFileWriter = new FileWriter(fileCurrentEvents, true);
for(int i = 0; i < namesArray.length; i++ ) {
currEventsFileWriter.write(namesArray[i]);
numSpaces = 20 - (namesArray[i].length() + 4);
for(int j = 0; j < numSpaces; j++) {
currEventsFileWriter.write("_");
}
currEventsFileWriter.write(ticketArray[i]);
currEventsFileWriter.write(String.format("%n"));
}
} catch(IOException e) {
System.out.println("Rewriting Current Events File Error");
System.exit(1);
}
try {
logoutFileWriter = new FileWriter(fileOutput, true);
//Cycle through event trans file and write via filewriter
for(int i = 0; i < eventTrans.size(); i++ ) {
String transact = eventTrans.get(i).toString();
logoutFileWriter.write(transact);
logoutFileWriter.write(String.format("%n"));
}
// Signify end of file
logoutFileWriter.write("00 000000 00000");
logoutFileWriter.write(String.format("%n"));
logoutFileWriter.close();
fileOutput.createNewFile();
} catch(IOException e) {
System.out.println("Output File Error");
System.exit(1);
}
return true;
/*
for( int i = 0; i < 20; i++ ) {
System.out.println("");
}
System.out.println("Logged Out");
consoleInput();
*/
}
public static void main(String[] args){
try {
File fileCurrentEvents = new File(args[0]);
fileOutput = new File(args[1]);
// Read current events file for events & dates
FileReader fileRead = new FileReader(fileCurrentEvents);
BufferedReader buffRead = new BufferedReader(fileRead);
// Create strings for data in current events file
String currentLine;
String eventName;
Integer numberTickets;
List<Integer> numticket = new ArrayList<Integer>();
List<String> list = new ArrayList<String>();
int[] numarray= new int[numticket.size()];
String[] linesArray = list.toArray(new String[list.size()]);
// Cycle through current events file line by line
while((currentLine = buffRead.readLine()) != null) {
if (currentLine.equals("END_________________00000")){
break; // End of file
}
//Parse for event name & number of tickets
eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
("_") + 1));
// Place event name and # tickets into data structure
// Add event name to event array list with same index as # tickets
// Parse int to get # tickets & add to arraylist for tickets with same index
while((eventName = buffRead.readLine()) != null){
list.add(eventName);
}
for (int i =0 ; i< list.size();i++){
linesArray[i]= list.get(i);
}
while((eventName = buffRead.readLine()) != null){
numticket.add(numberTickets);
}
for (int i =0 ; i< numticket.size();i++){
numarray[i]= numticket.get(i);
}
}
while(true) {
consoleInput(linesArray, numarray, fileCurrentEvents);
}
} catch (IOException e) {
System.out.println("File I/O Error"); //Print to console to signify error
e.printStackTrace();
System.exit(1);
}
}
}
If you are getting an ArrayOutOfBoundsIndexException at this line
File fileCurrentEvents = new File(args[0]);
Then it probably means the array (args) index (0) you are using is out of bounds in that it is higher than the size of the array.
If you have an array that looks like
[] //Zero entries
You can't get element 0 (the first item), because there are none.
So you must be passing in zero parameters when you run the code. Either when you run it at the command line, add the filename after it or change the build settings in your IDE (Eclipse, IntelliJ, Sublime) to add it to the build steps.
the error is being thrown on this line in the main method. File fileCurrentEvents = new File(args[0]);
Then your args is empty (e.g. you haven't run your program with any command line arguments, like a file). You could add a default, something like
File fileCurrentEvents = new File(args.length > 0 ? args[0] : "default.txt");
In your original code, line 763 is actually:
for (int i = 0 ; i< list.size(); i++){
linesArray[i] = list.get(i); //<--------------THIS ONE!
}
which can cause an ArrayIndexOutOfBoundsException when linesArray is shorter that list. This is happening because you instantiated linesArray earlier via
String[] linesArray = list.toArray(new String[list.size()]);
when list was empty, then added to list making it longer than your array.
Since the outer while-loop doesn't appear to use the linesArray in any other capacity, you can probably remove the above for-loop and, and place
linesArray = list.toArray(new String[list.size()]);
after the first while loop to create the appropriate array with all the elements.

How to get the nextInt after the nextInt but retain the value

My problem is instead of the fixed value of iValueNext, I want the next value on the excel sheet to run, which is 125,152,...
import java.util.*;
import java.io.*;
public class ConvertingData
{
public static void main (String [] args)
{
int i=1;
int j;
int iValue;
int iValueNext;
try
{
Scanner ifsInput = new Scanner(new File("input.csv"));
PrintStream ifsOutput = new PrintStream(new File("output.csv"));
while(ifsInput.hasNextLine())
{
String tokens[] = ifsInput.nextLine().split(",");
String Repeat = tokens[tokens.length - 1];
String Value = tokens[tokens.length - 3];
iValue = Integer.parseInt( Value );
for (i=iValue;i<=iValueNext;i++)
{
System.out.println(i+","+Repeat);
ifsOutput.println(i+","+Repeat);
}
}
ifsInput.close();
ifsOutput.close();
}
catch (FileNotFoundException sMsg)
{
System.out.println("File not found");
}
}
}
Here is part of the csv file:
89,31,31
125,1,32
152,-12,20
155,1,21
181,6,27
287,1,28
290,1,29
308,-8,21
If you need to "peek" at the next line while processing the current line, first read all the lines in:
List<String> lines = new ArrayList<String>();
while(ifsInput.hasNextLine()) {
lines.add(ifsInput.nextLine());
}
ifsInput.close();
then process the lines one by one with access to the next line:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String nextLine = i < lines.size() - 1 ? null : lines.get(i + 1);
String tokens[] = line.split(",");
String nextTokens[] = nextLine.split(",");
// whatever logic you need
ifsOutput.close();
}

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

Categories

Resources