Hey guys for some reason my code doesn't do anything when I compile it and I would appreciate if someone can figure it out, i am not very knowledgeable in java and coding in general and i tried fixing it and i got nothing i thought maybe it was the bufferedreader or the filereader but I'm not sure, so here is my code below
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Driver2 {
public static ArrayList < String > removeStopWords(String DTP3, String stopwords) throws IOException {
ArrayList < String > wordlst = new ArrayList < String > ();
ArrayList < String > stopwordlst = new ArrayList < String > ();
BufferedReader br1 = new BufferedReader(new FileReader("DTP3.txt"));
String line = "";
while ((line = br1.readLine()) != null) {
String[] words = line.split("[ ().!,:]");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().equals("") == false) {
wordlst.add(words[i]);
}
}
}
br1.close();
ArrayList < String > wordlstUpper = new ArrayList < String > ();
for (int i = 0; i < wordlst.size(); i++) {
wordlstUpper.add(wordlst.get(i).toUpperCase());
}
BufferedReader br2 = new BufferedReader(new FileReader("stopwords.txt"));
line = "";
while ((line = br2.readLine()) != null) {
stopwordlst.add(line);
}
br2.close();
for (int i = 0; i < stopwordlst.size(); i++) {
int lastindex = wordlstUpper.indexOf(stopwordlst.get(i).toUpperCase());
while (lastindex != -1) {
int index = wordlstUpper.indexOf(stopwordlst.get(i).toUpperCase());
if (index != -1) {
wordlst.remove(index);
wordlstUpper.remove(index);
}
lastindex = wordlstUpper.indexOf(stopwordlst.get(i).toUpperCase());
}
}
return wordlst;
}
public static void main(String[] args) {
ArrayList < String > list = null;
try {
list = removeStopWords("GPT3.txt", "stopwords.txt");
} catch (IOException e) {
System.out.print("Error : " + e.getMessage())
}
System.out.println("Non Stop Words are----");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
Related
I wrote code for a program that reads a file containing a list of numbers and outputs, for each number in the list, the next bigger number. I'm using eclipse for this project and when i go an run the program I'm getting an error and i cant seem how to fix it.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string:
"78,22,56,99,12,14,17,15,1,144,37,23,47,88,3,19"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at numbers.main(numbers.java:25)
Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class numbers {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> nextList = new ArrayList<Integer>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// read the list of number from file
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
// loop through each number
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int max = Integer.MAX_VALUE;
// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
// print the numbers
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + " : " + nextList.get(i));
}
} catch (FileNotFoundException e) {
// if file not found
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the file at the end
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
You need to split ( and also trim() ) your line over a comma (,) and then parse over all the elements you obtain.
Hope this solves your query.
The issue is you are trying to convert a string with multiple numbers to a single integer, which is causing your exception. Try this instead:
while ((text = reader.readLine()) != null) {
String [] textArray = text.split(",");
for (int i = 0; i < textArray.length; i++) {
list.add(Integer.parseInt(textArray[i]));
}
}
String line="";
while ((text = reader.readLine()) != null) {
line=text; //read the text
}
line.trim();
// loop through each number
for(String num:line.split(",")){
list.add(Integer.parseInt(num)); //add the item to the list
}
The text could have some non numeric characters so you should check about them so try like this
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
List<Integer> nextList = new ArrayList<>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text;
while ((text = reader.readLine()) != null) {// read the list of number from file
if(!text.isEmpty()) {
try {
if (text.contains(",")) {
for (String str : text.split(",")) {
list.add(Integer.parseInt(str));
}
}
else if(text.matches("[+-]?[0-9]+")) {
list.add(Integer.parseInt(text));
}
else {
System.out.println("this is not a number : " + text);
}
} catch (NumberFormatException e){
System.out.println("this is not a number : "+ text);
}
}
}
for (int i = 0; i < list.size(); i++) {// loop through each number
int num = list.get(i);
int max = Integer.MAX_VALUE;// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
for (int i = 0; i < list.size(); i++) {// print the numbers
System.out.println(list.get(i) + " : " + nextList.get(i));
}
}
catch (FileNotFoundException e) {// if file not found
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {// close the file at the end
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
}
}
}
this is a debugger error and runs an infinite loop where shown.
I am trying to load a file and have the gameboard be set to the chars in the text file (which are saved previously by user as shown) but in the debugger problem it sets next nextChar infinitely to □ after the first char has been read. I have had multiple attempts at trying to fix this myself but I cannot find a solution. Any help on how to fix this bug would be greatly appreciated. If any more details are needed give voice and see questions answered hastily.
This is the saving section of code.
/**
* A method to save the current state of the game
*/
public static void saveGame()
{
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
try
{
System.out.println("Please name the save game file.");
outputStream = new FileOutputStream(Genio.getString());
printWriter = new PrintWriter(outputStream);
int i, j =0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printWriter.println(gameBoard[i][j]);
}
}
}
catch (IOException e)
{
System.out.println("Sorry an error occured during saving.");
}
finally
{
if (printWriter != null)
{
printWriter.close();
}
}
}
This is the loading section of code;
/**
* A method to load a game.
*/
public static void loadGame()
{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
char nextChar;
String line;
try
{
System.out.println("Please enter the name of your save file:");
fileReader = new FileReader(Genio.getString());
bufferedReader = new BufferedReader(fileReader);
nextChar = (char)bufferedReader.read();
while ((line = bufferedReader.readLine()) != null)
{
for (int i=0; i<row; i++)
{
for (int j=0; j<col; j++)
{
if (nextChar == '-' || nextChar == 'Y' || nextChar == 'R') //Infinite loop here where nextChar = □
{
gameBoard[i][j] = nextChar;
nextChar = (char)bufferedReader.read();
System.out.print(gameBoard[i][j]);
line = bufferedReader.readLine();
}
else
{
nextChar = (char)bufferedReader.read();
j--;
}
}
System.out.print("\n");
}
line = bufferedReader.readLine();
}
System.out.println("1\t2\t3\t4\t5\t6\t7");
}
catch (IOException e)
{
System.out.println("Sorry an error occured during the loading of the file.");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
System.out.println("Sorry, an error has occured when closing the file.");
}
}
}
}
Not sure why you are reading a line AND reading characters.
You need to read each line and process each character in that line, for example...
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadConnect4 {
private static final String TEST_BOARD = "-------\n"
+ "-------\n"
+ "-------\n"
+ "-------\n"
+ "-Y-----\n"
+ "-Y--R--\n";
private static final int ROWS = 6;
private static final int COLS = 7;
public static void main(String[] args) throws Exception {
ByteArrayInputStream pretendFile = new ByteArrayInputStream(TEST_BOARD.getBytes());
char[][] board = readBoard(pretendFile);
printBoard(board);
}
private static void printBoard(char[][] board) {
for(int k = 0; k < board.length; k++) {
for(int j = 0; j < board[k].length; j++) {
System.out.print(board[k][j]);
}
System.out.println();
}
}
private static char[][] readBoard(InputStream stream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
int row = 0;
char[][] result = new char[ROWS][COLS];
// Read each line, stop when end of file (line is null)...
while((line = reader.readLine()) != null) {
// For each column...
for(int col = 0; col < 7; col++) {
// Get character from line, store in array
result[row][col] = line.charAt(col);
}
row++;
}
return result;
}
}
OUTPUT:
-------
-------
-------
-------
-Y-----
-Y--R--
To answer your question "why does it read box things", it's probably reading the end-of-stream and returning the character equivalent of "-1"
Trying to read in a maze in from a textfile to Java.
import java.io.*;
public class Maze {
private char[][]mazeData;
public static void main(String[] args) {
Maze test = new Maze();
}
public Maze() {
BufferedReader reader = null;
try {
File f = new File("c://testing.txt");
String line = null;
int row = 0;
reader = new BufferedReader(new FileReader(f));
reader.mark((int)f.length());
while ((line = reader.readLine()) != null) {
line = reader.readLine();
row++;
}
reader.reset();
mazeData = new char[row][];
row = 0;
while ((line = reader.readLine()) != null) {
mazeData[row++] = line.toCharArray();
}
int col=mazeData[0].length;
for (int i=0; i < row; i++){
for (int j=0; j < col; j++){
System.out.print(mazeData[i][j]);
}
System.out.println();
}
reader.close();
} catch (IOException e) {
System.out.println("INVALID FILE");
}
}
}
I tested in another class and java could find the file there so i dont get why the exeption keeps happening.
If you would print the catched exception you would read java.io.IOException: Mark invalid. Which is thrown at reader.reset(); because the mark has been invalidated.
You can fix it by
reader.mark((int)f.length() + 1);
Anyway there is no need to process the file twice only to know the number of lines. You can read all lines into a List<String> and process the lines from that array.
List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"),
Charset.defaultCharset());
edit
A stripped down solution (based on your code) could be.
public class Maze {
private char[][] mazeData;
public static void main(String[] args) {
Maze test = new Maze();
}
public Maze() {
try {
List<String> lines = Files.readAllLines(Paths.get("c:/testing.txt"), Charset.defaultCharset());
mazeData = new char[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
mazeData[i] = lines.get(i).toCharArray();
}
int columns = mazeData[0].length;
int rows = lines.size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(mazeData[i][j]);
}
System.out.println();
}
} catch (IOException ex) {
System.out.println("failed: " + ex.getMessage());
}
}
}
Keep few other comments:
- avoid to do I/O processing in a constructor
- split the code in logical blocks (one method per logical step), e.g. initMazed(), printMaze(), etc.
I am writing a simple bigram frequency count algorithm in Java and encountering a problem I don't know how to fix.
My source file is a 9MB .txt file with random words, separated by spaces.
When I run the script limiting the input to the first 100 lines, I get a value of 1 for the frequency of the bigram "hey there".
But when I remove the restriction to only scan the first 100 lines and instead scan the entire file, I get a value of null for the same bigram search. The key/value pair in the HashMap is now null.
I am storing all the bigrams in a HashMap, and using a BufferedReader to read the text file.
What is causing the bigram (key) to be removed from or overwritten in the HashMap? It shouldn't matter if I am reading the entire file or just the first part of it.
public class WordCount {
public static ArrayList<String> words = new ArrayList<String>();
public static Map<String, Integer> bi_count = new HashMap<String, Integer>();
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
System.out.println("\nProcessing file...");
while (br.readLine() != null) {
// for (int i = 0; i < 53; i++ ) {
sCurrentLine = br.readLine();
if (sCurrentLine != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
countWords();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void countWords() {
for (int k = 0; k < words.size(); k++) {
String word = words.get(k);
String next = "";
if (k != words.size() - 1) {
next = words.get(k+1);
}
String two_word = word + " " + next;
if (bi_count.containsKey(two_word)) {
int current_count = bi_count.get(two_word);
bi_count.put (two_word, current_count + 1);
}
else {
bi_count.put( two_word, 1);
}
}
System.out.println("File processed successfully.\n");
}
I'm not totally confident this is the cause of your problem, bot you are not reading all lines of your input file.
while (br.readLine() != null) {
sCurrentLine = br.readLine();
The line read in the if() statement is not being processed at all - you are missing alternate lines.
Instead try this:
while ((sCurrentline = nr.readLine()) != null) {
//now use sCurrentLine...
}
This block of code is wrong because readline is called twice:
while (br.readLine() != null) {
// for (int i = 0; i < 53; i++ ) {
sCurrentLine = br.readLine();
if (sCurrentLine != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}
}
I would suggest:
while ((sCurrentline = nr.readLine()) != null) {
String[] input_words = sCurrentLine.split("\\s+");
for (int j = 0; j < input_words.length; j++) {
words.add(input_words[j]);
}
}
I am trying to create a 2d array using the contents of a text file, however I am unable to return it. It says it cannot find the symbol firstDimension, however I declared it within the method.
import java.io.*;
import java.util.*;
public class Map {
public static char[][] readFile() {
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
}
firstDimension is declared within your try block hence its scope is that try block. to be able to return it outside the try block, you need to declare it as follows:
public static char[][] readFile() {
char[][] firstDimension = null;
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
In that case, if an exception is encountered, your method could return null.
This is another example of the same issue.