Why is my Integer.parseInt not working? - java

The assignment is to create an output that reads from a file and outputs the information that is stated in the program. It was working perfectly before I went back and added the patientNumber string and the first for loop that deals with patientNumber. Now it is showing the error that the line with Integer.parseInt is not working. What happened?
package readfile;
import java.io.*;
public class ReadFile {
public static void main(String[] args)
{
String[] patientNumber = new String [15];
String[] patientFN = new String[15];
String[] patientLN = new String[15];
int[] patientBP = new int[15];
String lastnameBP = " ";
String all=" ";
int x = 0;
String Heading1 = "Patient #";
String Heading2 = "First Name";
String Heading3 = "Last Name";
String Heading4 = "Patient BP";
String Underl = "--------------------------------------------";
System.out.printf("%10s %10s %10s %10s", Heading1,Heading2,Heading3,Heading4);
System.out.println();
System.out.println(Underl);
String fileName="patient.txt";
//Name of the file with precise directory
//String fileName="patient.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
//assigning patient number, first name, last name, and BP
for(int i=0; i<line.length(); i++){
if(line.charAt(i) == ' ')
{
patientNumber[x] = (line.substring (0,i));
all = line.substring(i+1, line.length());
}
}
for(int i=0; i<all.length(); i++)
{
if(all.charAt(i) == ' ')
{
patientFN[x] = all.substring(0,i);
lastnameBP = all.substring(i+1, all.length());
break; //breaking loop
}
}
for(int i =0; i < lastnameBP.length();i++) {
if(lastnameBP.charAt(i) == ' ') {
patientLN[x]= lastnameBP.substring(0, i);
patientBP[x] = Integer.parseInt(lastnameBP.substring(i + 1, lastnameBP.length()));
break;
}
}
x++;
}
//Close the buffer reader
bufferReader.close();
}catch(IOException e){
//At the top print your titles with format characters
// Each column is 10 Characters and left justified ("%-10s")
System.out.println("Error while reading file line by line:" + e.getMessage());
}
for(int k=0; k< 15; k++) {
System.out.printf("&-10s", patientNumber[k]);
System.out.printf("%-10s", patientFN[k]);
System.out.printf("%-10s", patientLN[k] );
System.out.printf("%-10s", patientBP[k] );
System.out.println();
}
}
}
This is the error message:
Patient # First Name Last Name Patient BP
--------------------------------------------
Exception in thread "main" java.lang.NumberFormatException: For input
string: ""
at
java.lang.NumberFormatException.forInputString
(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at readfile.ReadFile.main(ReadFile.java:74)
C:\Users\wking\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Looks like you have trouble with finding the number you want to parse. May I suggest you simplify your main loop to something like the following:
while ((line = bufferReader.readLine()) != null) {
String[] parts = line.trim().split(" ");
patientNumber[x] = parts[0];
patientFN[x] = parts[1];
patientLN[x] = parts[2];
patientBP[x] = Integer.parseInt(parts[3]);
x++;
}

Related

Split lines with "," and do a trim on every element [duplicate]

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Array doesn't retain its value after being written to

I'm trying to read a file into an array, each line will be store in an index of the array. Given the following input in the text.txt file :
6afe
5af
3eafe
7fae
3sfs
1eef
I read into the array, then printout the array in the console to check, but somehow the array doesn't retain its value after the loop. The output I got was null, before and after, but not in middle of the loop. Please tell me why ? Thank you
Here are the output I get
nullline 0
nullline four
6afe
5af
3eafe
7fae
3sfs
1eef
nullline three
nullline four
The output I epxected to get are :
nullline 0 // array still empty here, i get it
nullline four // array still empty
6afe
5af
3eafe
7fae
3sfs
1eef
7fae // where here are null three ? in the actual ouput
3sfs // null three ?
And here is my code :
import java.io.*;
public class readSortWrite
{
public static void main(String[] args) throws java.io.IOException
{
//input file
// to count lineNum
FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr);
//to read into array names[]
FileReader fr1 = new FileReader("text.txt");
BufferedReader br1 = new BufferedReader(fr1);
// output file
FileWriter fw = new FileWriter("sorted.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
// counting number of line
int lineNum = 0;
String line;
line = br.readLine();
while(line != null)
{
lineNum++;
line = br.readLine();
}
pw.close();
// System.out.println(lineNum + "lines");
// create an array of of lineNum size and write each line of file into array
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
// fr1.close();
System.out.println(names[3]+ " line three");
System.out.println(names[4] + " line four");
}
}
first 2 lines are null cause you create the array and print the values at 0 and 4 indices before init them, like so
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for the second last rows, the while loop will read the buffer till it empty but without any iteration of the for loop, thus only populated names[0]
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
change it to something like
int i =0;
while (str!= null && i < lineNum) {
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
The error lies in the nested loops used to read the file into array
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
so for the first value of i you read The entire input file. when you wxit the nested while loop, the entire file has been read, but the index remained the same.
yuo should have one loop that reads the file, and the index is advanced at each iteration
int i = 0;
while (str!= null)
{
names[i] = str;
i++;
str = br1.readLine();
System.out.println(names[i]);
}
You declare and instantiate names:
String[] names = new String[lineNum];
but after that you haven't put anything into names when you try to print:
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
In the for loop that follows you are overwriting names[0] repeatedly. The while loop executes using 0 as the value of i.
Just replace it with the code below. You were using a while true
String str;
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
for (int i = 0 ; i<lineNum; i++)
{
str = br1.readLine();
if (str!= null)
{
names[i] = str;
System.out.println(names[i]);
}
}
String[] names = new String[lineNum];
String str;
str = br1.readLine();
System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");
the code you just create names[], so output is null.
for (int i = 0 ; i<lineNum; i++)
{
while (str!= null)
{
names[i] = str;
str = br1.readLine();
System.out.println(names[i]);
}
}
the code ,when i=0 ,you enter while and not break,so System.out.println(names[i]); always output names[0] until the last str.
and names[] other element is always null.

Java word appearence in a text file

For the given text file (text.txt) compute how many times each word appears in the file. The output of the program should be another text file containing on each line a word and then the number of times it appears in the original file. After you finish change the program so that the words in the output file are sorted alphabetically. Do not use maps, use only basic arrays. The thing is displaying me only one word that I enter from keyboard in that text file, but how can I display for all words, not only for one? Thanks
package worddata;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class WordData {
public FileReader fr = null;
public BufferedReader br =null;
public String [] stringArray;
public int counLine = 0;
public int arrayLength ;
public String s="";
public String stringLine="";
public String filename ="";
public String wordname ="";
public WordData(){
try{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the filename: ");
filename = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter a word: ");
wordname = scan.nextLine();
fr = new FileReader(filename);
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
//System.out.println(s);
stringLine = stringLine + " ";
counLine ++;
}
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
if (stringArray[i].equalsIgnoreCase(wordname)){
System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
}
}
}
}
System.out.println("Total number of lines: "+counLine);
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
OutputStream out = new FileOutputStream("output.txt");
System.out.println("Please enter the filename: ");
String filename = scan.nextLine();
System.out.println("Please enter a word: ");
String wordname = scan.nextLine();
int count = 0;
try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
String line;
while ((line = r.readLine()) != null) {
for (String element : line.split(" ")) {
if (element.equalsIgnoreCase(wordname)) {
count++;
System.out.println("Word found at line " + r.getLineNumber());
}
}
}
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("The word " + stringBuffer.toString() + " appears " + count + " times.");
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 1000; i++) {
String str = null;
str = +i + ":- The word "+wordname+" was found " + count +" times";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code below does something like you want I think.
it does the following:
read the contents from the input.txt file
Remove punctuation marks from the text
make it one string of words by removing line breaks
Split the text up in words by using space as delimiter
The lambda maps all the words to lowercase then removes whitespace and all empty entries then it...
loops over all words and computes there word count in het HashMap
then we sort the Map based on the count value in reverse order to get the highest counted words first
then write them to a StringBuilder to format it like this "word : count\n" and then write it to a text file
final String content = new String(Files.readAllBytes(Paths.get("<PATH TO YOUR PLACE>/input.txt")));
final List<String> words = Arrays.asList(content.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").replace("\n", " ").split(" "));
final Map<String, Integer> wordlist = new HashMap<>();
words.stream()
.map(String::toLowerCase)
.map(String::trim)
.filter(s -> !s.isEmpty())
.forEach(s -> {
wordlist.computeIfPresent(s, (s1, integer) -> ++integer);
wordlist.putIfAbsent(s, 1);
});
final StringBuilder sb = new StringBuilder();
wordlist.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
)).forEach((s, integer) -> sb.append(s).append(" : ").append(integer).append("\n"));
Files.write(Paths.get("<PATH TO YOUR PLACE>/output.txt"), sb.toString().getBytes());
Hope it helps :-)
Note: the <PATH TO YOUR PLACE> needs to be replaced by the fully qualified path to your text file with words.

Array/Loop does not output primary line

I'm having a small problem with my code and I'm not exactly sure how to fix it.. Basically I'm trying to separate the file into different lines (Frames) and then input those lines into the file, and proceed to print them. My first line of the file never prints.
public class Main {
public static void main(String[] args) throws IOException
{
/*Switch switcherino = new Switch();*/
Frame frame = new Frame();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to process: ");
String fileName = input.nextLine();
FileInputStream inputStream =
new FileInputStream(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream,Charset.forName("UTF-8"));
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
try{
String str = " ";
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
}
catch (IOException e){
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I don't want to use an ArrayList, as much as it would probably be easier.
Thanks in advance!
File: (switch.txt)
fa00 123123123abc 111111222222 data1
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
Output: (from System.println(words[i]);)
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
This is wrong logic: you read the line, you split it into words so then go ahead and print them - no need to try and read any more lines
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
use this instead
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
System.out.println(words[i]);
}
}
// to count length
int length = 0;
BufferedReader br =
new BufferedReader(inputStreamReader);
while(true){
str = br.readLine();
if(str == null) break;
else length++;
} // this loop counts the length!!
final int clength = length;
//now this is what you want!
String words[] = new String[clength];
int j= 0;
while(true){
str = bufferedReader.readLine();
if(str == null) break;
words[j++] = str;
System.out.println(str); //FIXED
}
//Now the words[] have all the lines individually
Your code doesn't work because you called readLine() twice, which skipped the first line. Try this and let me know.
You don't need to use split() since you want the entire line :)
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
When iterate the file, you split your first line into a String array,
words[] contains the following elements : fa00, 123123123abc, 111111222222 and data1.
and then the inner for loop iterate your bufferReader and you assign the lines to a specific index of word and then you print out the word array elements
You are not supposed to invoke bufferedReader.readLine() in the inner for loop, it breaks your logic.

StringIndexout of range

I got an error: StringIndex out of range: -1 with error line is String anEmail = lineFromFile.substring(s+1, e). As you can see im trying to print a part of a line in an input file but i doesn't work. Can someone help me explain why?
import java.io.*;
public class Email13
{
static boolean isValidEmailCharacter(char c)
{
boolean result = false;
if((c>='A'&&c<='Z')||(c>='a'&&c<='z')||(c>='0'&&c<='9')||(c=='.')||(c=='-')||(c=='+'))
result = true;
return result;
}
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 start the final project.");
System.out.println();
String nameIn, nameOut, deIn, deOut;
nameIn="";
nameOut="";
deIn = "fileContainingEmails.txt";
System.out.print("Enter input filename [default:" + deIn + "]: ");
nameIn = cin.readLine();
if(nameIn.compareTo("")==0){
nameIn = deIn;
deOut = "copyPasteMyEmails.txt";
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = deOut;
}
else if(nameIn.compareTo("")>0){
deOut = nameIn;
System.out.print("Enter output filename [default:" + deOut + "]: ");
nameOut = cin.readLine();
if(nameOut.compareTo("")==0)
nameOut = nameIn;
}
fin = new BufferedReader(new FileReader(nameIn));
//Read the input file
while(true)
{
if(!fin.ready()) break;
String lineFromFile;
lineFromFile = fin.readLine();
int s, e, hasDot;
for (int i = 0; i < lineFromFile.length(); i++) // for each char in the string...
{
if(lineFromFile.charAt(i)=='#')
{
for(s=i;s>-1;s--)
{
if(isValidEmailCharacter(lineFromFile.charAt(s))==false)
for(e=1; e< lineFromFile.length(); e++)
{
if(isValidEmailCharacter(lineFromFile.charAt(e))==false)
{
String anEmail = lineFromFile.substring(s+1, e);
System.out.println(anEmail);
break;
}
}
}
}
}
}
fin.close();
PrintWriter fout;
fout = new PrintWriter(new FileWriter(nameOut));
fout.close();
}
}
Suppose a line has 10 characters. So i loop goes from 0 to 9.
You then have a s loop, which goes from i to 0.
And inside that, you access `linefromFile.subString(s+1);
So when i is 9, your s loop starts at 9, and you try to access index 9+1, which is index 10, which is outside of your line.
Since Arrays are zero based indices, your lineFromFile.substring(s+1, e) is throwing an error.
for(s=i;s>-1;s--){
//lines of code
String anEmail = lineFromFile.substring(s+1, e)
This would fail for i = lineFromFile.length
as it would translate to lineFromFile[i+1] where lineFromFile[i] is the last element.

Categories

Resources