Array doesn't retain its value after being written to - java

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.

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.

How can i use splitter ^ in java

I have a problem with my java program. I have to read lines from a file, the form of these lines is:
1#the^cat#the^dog#the^bird#^fish#bear
2#the^cat#the^dog#the^bird#^fish#bear
and print all, accept the "#" and "^" at textfields in my GUI. The "^" must appear in case there in not article. For exaple ^fish, i have to print it as ^fish but the^dog i have to print the dog.
As far i can read and print the lines in the textfields but i can't find a way to skip the "^" between the words.
Here is my code:
try {
FileReader file = new FileReader("C:\\Guide.txt");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i=0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line "+i+" <"+line+">");
String[] words = line.split("#");
if (words.length != 7) continue;
number=words[0];
onomastiki=words[1];
geniki=words[2];
aitiatiki=words[3];
klitiki=words[4];
genos=words[5];
Region=words[6];
E = new CityEntry(number,onomastiki,geniki,
aitiatiki,klitiki,
genos,Region);
Cities.add(E);
}
You can try something like this.
FileReader file = new FileReader("C:\\\\Users\\\\aq104e\\\\Desktop\\\\text");
BufferedReader BR = new BufferedReader(file);
boolean eof = false;
int i = 0;
while (!eof) {
String line = BR.readLine();
if (line == null)
eof = true;
else {
i++;
System.out.println("Parsing line " + i + " <" + line + ">");
String[] words = line.split("#");
for (int j = 0; j < words.length; j++) {
if(words[j].contains("^")) {
if(words[j].indexOf("^") == 0) {
// write your code here
//This is case for ^fish
}else {
// split using ^ and do further manipulations
}
}
}
}
}
Let me know if this works for you.
That is gonna work, but it is not best way)
foreach(String word : words){
if(word.contains"the"){
word.replace("^"," ");
}
}

Why is my Integer.parseInt not working?

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

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.

java regular expression getting values from a txt file [duplicate]

I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
Now what I want is, I need to get "a" and "b" as two different array list.
You need to read the file line by line. It is done with a BufferedReader like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Assuming your "a" and"b" are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double :
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
Array[] first= line.split("("); //first[2] will contain the values
Then:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.

Categories

Resources