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) {
}
}
}
Related
I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}
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.
Input file-
5
1 2 3 4 5
2 3 4 5 6
3 2 1 5 8
My work is i should read this input file my.txt and swap its first and last column and output it to another file comp.txt but I am getting a blank file comp.txt
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintStream;
import java.io.*;
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int row = 0;
private static int column = 0;
private static int[][] matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
int lineNum = 0;
int row = 0;
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
while ((line = in.readLine()) != null)
{
lineNum++;
if (lineNum == 1)
{
column = Integer.parseInt(line);
}
else
{
String[] tokens = line.split(",");
for (int j = 0; j < tokens.length; j++)
{
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
else matrix[row][j] = Integer.parseInt(tokens[j]);
}
row++;
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
}
finally
{
if (in != null) in.close();
}
try
{
PrintStream output = new PrintStream(new File("comp.txt"));
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
output.println(matrix[i][j] + " ");
}
}
output.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Here is the output I am getting at console-
The code throws an exception
null
Apart from this I am getting a blank comp.txt file
After I replaced your catch block with
catch (Exception ex)
{
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
I could tell that the error is
java.lang.NullPointerException
at test.example.code.Swap.main(Swap.java:37)
The code throws an exception
null
Where the line is
if (j == 0) matrix[row][0] = Integer.parseInt(tokens[column]);
Because you are trying to access the 5th column of tokens but it's actually a 5-length array and indices in Java and most C-based languages in general are zero-indiced aka the valid indices are from 0 to 4.
Also, I'm not entirely sure what you are trying to do with this line, so I won't fix it, but that's the error.
EDIT:
Now this is not exactly a legitimate thing to do, but I solved it as I would have done it myself, and I will explain it afterwards. If you mustn't read the code because your "mentor" would be against it, then just read the final lines of this post and solve it on your own.
// to swap first and last column of 2D array
public class Swap
{
private static BufferedReader in = null;
private static int column = 0;
private static List<int[]> matrix = null;
public static void main(String[] args) throws Exception
{
try
{
// String filepath = args[0];
in = new BufferedReader(new FileReader("my.txt"));
String line = null;
matrix = new ArrayList<int[]>(); //array length is variable length
//so using a 2D array without knowing the row size is not right
boolean isFirstLine = true;
while ((line = in.readLine()) != null)
{
if (isFirstLine)
{
column = Integer.parseInt(line); //first line determines column length
isFirstLine = false;
}
else
{
String[] tokens = line.split(" "); // there are no commas in input file so split on spaces instead
matrix.add(new int[column]);
for (int i = 0; i < tokens.length; i++)
{
matrix.get(matrix.size() - 1)[i] = Integer.parseInt(tokens[i]);
//store the lines of the currently read line in the latest added array of the list
}
}
}
}
catch (Exception ex)
{
System.out.println("The code throws an exception");
ex.printStackTrace(); //changed exception write out for better info
}
finally
{
if (in != null)
in.close();
}
// swapping the elements of first and last in each int array of list
for(int[] intLines : matrix)
{
int temp = intLines[0];
intLines[0] = intLines[intLines.length-1];
intLines[intLines.length-1] = temp;
}
BufferedWriter output = null;
try
{
output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
"comp.txt")))); //i just prefer bufferedwriters don't mind me
output.write("" + column); //write the first line that is the array length into file
output.newLine();
for (int[] intLines : matrix) //write out each line into file
{
for (int i = 0; i < intLines.length; i++)
{
output.write("" + intLines[i]);
if (i < (intLines.length - 1))
{
output.write(" ");
}
}
output.newLine();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if (output != null)
{
try
{
output.close();
}
catch (IOException e)
{
}
}
}
}
}
So basically I changed the 2D array to a list of arrays, read in the file, fixed that you were splitting along commas instead of spaces, and actually did the swap. You don't necessarily have to take this approach, especially if that is against the rules. Don't even read the code if you mustn't.
1) Change
System.out.println("The code throws an exception");
System.out.println(ex.getMessage());
To get detailed description for cause of exception.
System.out.println("The code throws an exception");
ex.printStackTrace();
2) From code & exception message it seems like there is a NullPointerException as ur array matrix is initialized to null and not to array of matching size.
So solution to the exception is[Assuming your core logic is fine] , before assigning any values to matrix array, initialize with relevant size i.e with max rows & columns
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]);
}
}