Why does my summation program throw a NumberFormatException? - java

I want to read the numbers from the file and sum up the total, but I cannot seem to process the data properly. It is successfully outputting the numbers but is not successfully summing them up.
My code:
import java.io.*;
import java.util.*;
public class Q1 {
public static void main(String[] args) throws IOException {
StringBuffer str = new StringBuffer();
FileWriter output = new FileWriter("number.txt");
Random r = new Random();
for (int i = 1; i < 101; i++) {
str.append(r.nextInt(100) + " ");
}
output.write(str.toString());
System.out.println(str.toString());
output.close();
FileReader reader = new FileReader("number.txt");
BufferedReader input = new BufferedReader(reader);
String line = input.readLine();
int total = 0;
while (line != null) {
System.out.print(line);
total += Integer.parseInt(input.readLine());
}
System.out.println(total);
}
}
And the stacktrace:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Q1.main(Q1.java:42)

You don't append a ending line char to the output.
Try out this snippet:
StringBuffer str = new StringBuffer();
FileWriter output = new FileWriter("number.txt");
Random r = new Random();
for (int i = 1; i < 101; i++) {
str.append(r.nextInt(100)).append('\n');
}
output.write(str.toString());
System.out.println(str.toString());
output.close();
FileReader reader = new FileReader("number.txt");
BufferedReader input = new BufferedReader(reader);
String line;
int total = 0;
while ((line = input.readLine())!=null) {
total += Integer.parseInt(line);
}
System.out.println(total);
If the output looks weird, examine where the output is being created. That is usually where you will find the problem. Also added in some small changes to give you an idea of a different way you could go about it that might make your life easier.

Related

java BufferedReader & Writer doesn't work as expected

What I was trying to do was to read a mnist train file, and express it's first digit in eleven digits, and keep other same.
So 3,1,4,6 ... to ,0,0,0,1,0,0,0,0,0,0,1,4,6... (there's "" at first digit so total 11 digits)
I thought it's an easy job but it wasn't.
import java.io.*;
public class T {
public static void main(String[] args){
File file = new File("./src/dataset/mnist_train.csv");
File wfile = new File("./src/dataset/conv_mnist_train2.txt");
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(wfile));
String line;
String[] numbers;
int g = 0, cnt = 0, cnt2 = 0;
while ((line = bufferedReader.readLine()) != null) {
cnt2++;
numbers = line.split(",");
for(String i : numbers){
if(g == 0){
for(int j=0; j<10; ++j) {
if(j == Integer.parseInt(i)) fileWriter.write("," + 1);
else{ fileWriter.write("," + 0); cnt++;}
}
g++;
}
else {fileWriter.write("," +i); cnt++;}
}
fileWriter.newLine();
System.out.println(numbers.length + " " + cnt + " " + cnt2);
g = 0; cnt = 0;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
g, cnt, cnt2 are numbers I used for debugging but I didn't find any problem here; it naturally converted each lines with 785 letters into new lines with 795 letters.
import java.io.*;
public class Tes {
public static void main(String[] args){
File file = new File("./src/dataset/conv_mnist_train2.txt");
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
int g = 0;
while ((line = bufferedReader.readLine()) != null) {
g++;
String[] N = line.split(",");
if(N.length != 795){
System.out.println(N.length + " " + g);
for(String i : N) System.out.print(i + " ");
System.out.println();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
But what happened is that when I run my second code, which shouldn't print anything, printed result and said my 59994th row data is only consisted of 311 letters. But from my first code, I confirmed that my 59994th row has 795 letters. I don't know what's going on here.
Also I tried to use FileWriter and FileReader instead of BufferedWriter & Reader, but it didn't solve problem. Could somebody tell me what's going on, and how to fix this?
The problem was that I didn't close the reader/writer. Didn't know it could end up in serious error.

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.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 need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

Replace letters with *

Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}
If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();
Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));
Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}

Index out of bounds error when parsing to Integer

I am getting an error when trying to parse from a String to an Integer or a double.
int id = Integer.parseInt(stringParts[2]);
If I print stringParts[2] it works, it only throws an error when parsing.
This is the complete loop I'm using:
public static StudentRecord[] creates(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("/Users/DNA40/Desktop/lab11input.txt"));
int lineText = lineCount("/Users/DNA40/Desktop/lab11input.txt");
String record;
String cons = ("[ ]");
StudentRecord[] student = new StudentRecord[lineText];
String[] stringParts = new String[5];
for(int i = 0; i < lineText ; i++){
student[i] = new StudentRecord();//Creates Object class
record = br.readLine(); //Stores the first line of text file
stringParts = record.split("\\s+");//Splits the line into parts
student[i].setFirstName(stringParts[0]);
student[i].setLastName(stringParts[1]);
int id = Integer.parseInt(stringParts[2]);
student[i].setID(id);
double gpa = Double.parseDouble(stringParts[3]);
student[i].setGPA(gpa);
int hours = Integer.parseInt(stringParts[4]);
student[i].setHours(hours);
}
return student;
}
public static int lineCount(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int count = 0;
String currentLine;
while ((currentLine = br.readLine()) != null){
count++;
}
return count;
}
It generates error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
Thank you
Index out of bounds means that
stringParts[2]
does not exist. Check the length of the array. The split probably isent working as you would expect

Count number of * from text file

I have this code to count the number of * from a string entered. but I need to find it from an text file. Any idea?
import java.lang.String;
import java.io.*;
import java.util.*;
public class CountStars {
public static void main(String args[]) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String text = bf.readLine();
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='*' ) {
count++;
}
}
System.out.println("The number of stars in the given sentence are " + count);
}
}
Use a FileInputStream and a InputStreamReader together, while specifying the character-encoding. "UTF-8" is a pretty safe bet. Then read each line and count the number of '*' characters as you already did. Then create a grand total and don't forget to close the file afterwards.
We can write something as simple as below:
int count= 0;
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String text;
while((text= br.readLine()) != null) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='*' ) {
count++;
}
}
}
System.out.println("Count Stars = "+ count);
Replace BufferedReader line with below lines.
Path path = Paths.get(aFileName);
BufferedReader bf = Files.newBufferedReader(path, ENCODING)
where aFileName is the file path, you can either use args or make a function.
Update1:
Thanks owlstead.
Use following line if version < 7.
BufferedReader bf = new BufferedReader (new FileReader (aFileName));
Regards,
Tamour

Categories