Grid index Structure - java
* *
I learn a grid index structure. so far i have created data generator called data_gen.jar
here is the format output data from data_gen
Each line consists of ID, x1, y1, x2, and y2 that represent a rectangle
let's say that this data store into text called input_data_set.txt
now my next steps are, first: make another program to do this
./gri -m page_capacity -l object_list_size -h -f input_data_set
-m: Number of points in a disk page.
-l: Number of points can be stored in memory.
-h: Use Hilbert order to compute ordering number. Default is row
ordering.
-f: Input filename.
After executing the command,three files gri.conf, gri.idx and gri.iof must be produced.
in grid.conf we store the configurations
For simplicity, we assume page size of the gri.iof file is sufficient to store overflow points. This implies you can drop some points
when the points number exceeds capacity of a page of the gri.iof file. One can also adjust the data-set to
prevent from too many overflow points.
here is the figure for more detail
then, After construction, use following command to enter an interactive mode
./gri -i [-c cache_size] -h
I)nsert
D)elete
Q)uery/Index
U)pdate
cmd>
Users can type command to interact with the gri. Following is a simulation.
./gri -i -c 4 -h
cmd> I 4:8,9,8,9
gri: Point 4 is inserted into cell(x, y).
cmd> Q 4:8,9,8,9
gri: Point 4 is stored at cell(x, y), page 2.
gri: Page 2 includes points: 3, 4.
gri-cache: 2, 3, 4, 5 #disk page number
cmd> D 4:8,9,8,9
gri: Point 4 is deleted from cell(x, y), page 2.
gri: Page 2 includes points: 3.
cmd> U 4:8,9,8,9 1,2,1,2
gri: Point 4 is migrate from page 2 to page 0.
gri-cache: 4, 5, 1, 0
in case, i'm doing in java..
does anyone could help me or guide me.. any reference would be great
i'm confusing for the next step, i have only succeed in data generator
here is some code
GRI.java
package gri;
import java.io.*;
public class GRI
{
public static void main(String[] args) throws IOException
{
String strin="null";
BufferedReader buf;
int M=4,N=10000;
double Sx=100,Sy=100;
int method=1;
int timestamp=1;
System.out.println("Please enter the number of data:");
buf=new BufferedReader(new InputStreamReader(System.in));
strin=buf.readLine();
N=Integer.parseInt(strin);
System.out.println("Please enter a page capacity (M):");
strin=buf.readLine();
M=Integer.parseInt(strin);
System.out.println("Please enter Sx:");
strin=buf.readLine();
Sx=Double.parseDouble(strin);
System.out.println("Please enter Sy:");
strin=buf.readLine();
Sy=Double.parseDouble(strin);
System.out.println("N: "+N+" "+"M:"+M+" "+"Sx:"+Sx+" "+"Sy:"+Sy);
int count_d=N; //Record number of existing information
// System.out.println("請選擇index方式:");
System.out.println("1.row order");
System.out.println("2.Z-Curve");
// strin=buf.readLine();
// method=Integer.parseInt(strin);
System.out.println("Please enter K:");
strin=buf.readLine();
int k=Integer.parseInt(strin);
System.out.println("Please X% of the point before entering as a query: ");
strin=buf.readLine();
int x=Integer.parseInt(strin);
int query_num=N/100*x;
System.out.println("query number: "+query_num);
String temp=Integer.toString(N);
int N_len=temp.length();
temp="X";
for(int i=0;i<N_len+15-1;i++)
{
temp=temp+"X";
}
double grid=0;
int grid_i=0,cell=0;
cell=(int)Math.ceil((double)N/M); //至少需幾個cells 取大於的最小整數
grid=Math.sqrt(cell); // ? x ? 的?
grid_i=(int)Math.ceil(grid); // ? 取大於的最小整數 grid_i x grid_i
int grid_z=1;
if(method==2)
{
while(grid_z<grid_i)
{
grid_z*=2;
}
grid_i=grid_z;
}
System.out.println("至少需cell:"+cell+" "+"幾乘幾:"+grid_i+" x "+grid_i);
double cellx=Sx/grid_i; // 一格的 x 分量
double celly=Sy/grid_i; // 一格的 y 分量
System.out.println("一格的 X 分量:"+cellx+" "+"一格的 Y 分量:"+celly);
//輸出 設定檔
FileWriter fw3 = new FileWriter("gri.conf");
BufferedWriter bfw3 = new BufferedWriter(fw3);
bfw3.write("size of data: "+N);
bfw3.newLine();
bfw3.write("page capacity: "+M);
bfw3.newLine();
bfw3.write("grid size: "+grid_i+" x "+grid_i);
bfw3.newLine();
bfw3.write("一格的 X 分量: "+cellx+" 一格的 Y 分量: "+celly);
bfw3.newLine();
bfw3.flush();
fw3.close();
String str;
FileReader fr = new FileReader("stdout1.txt");
BufferedReader bfr = new BufferedReader(fr);
//orderfile空間
FileWriter fw = new FileWriter("gri.idx");
BufferedWriter bfw = new BufferedWriter(fw);
//規劃overflow空間
FileWriter fw2 = new FileWriter("gri.iof");
BufferedWriter bfw2 = new BufferedWriter(fw2);
//開始規劃
for(int i=0;i<grid_i*grid_i;i++)
{
String disk_p="#";
for(int j=0;j<N_len-Integer.toString(i).length();j++)
disk_p=disk_p+"0";
disk_p=disk_p+Integer.toString(i);
bfw.write(disk_p);
bfw.newLine();
bfw2.write(disk_p);
bfw2.newLine();
for(int j=0;j<M;j++)
{
bfw.write(temp);
bfw.newLine();
bfw2.write(temp);
bfw2.newLine();
}
}
bfw.flush();
fw.close();
bfw2.flush();
fw2.close();
// System.out.println("orderfile & overlfow create");
File file = new File("gri.idx");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
File file2 = new File("gri.iof");
RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
//建index
while( ( str=bfr.readLine() )!=null ) //從stdout.txt讀取
{
int ci=0,cj=0; // 以 row ordered 的編號
int disk_p=0;
int overflow=0;
String diskcon; //應放位置
String[] str_arr = str.split(" "); // str_arr[0]=ID, str_arr[1]=Xlow , str_arr[2]=Ylow...
String data=str_arr[0]+" "+str_arr[1]+" "+str_arr[2];
ci=(int) Math.ceil( (Double.parseDouble(str_arr[1])/cellx) );
cj=(int) Math.ceil( (Double.parseDouble(str_arr[2])/celly) );
// System.out.println(ci+" "+cj);
disk_p=(cj-1)*grid_i+ci-1; //DISK中的位置 -1因為從0開始
if(method==2) //以Z_ORDER的方式計算
disk_p=cul_zorder(ci,cj);
//not need
String pos = "#";
for(int i=0;i<N_len-Integer.toString(disk_p).length();i++)
pos=pos+"0";
pos+=Integer.toString(disk_p);
//not need
// System.out.println(disk_p);
raf.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 ); //搜尋區塊
for(int i=0;i<M;i++) //檢查此區塊是否已存M點
{
if((diskcon=raf.readLine()).equals(temp))
{
raf.seek(raf.getFilePointer()-17-N_len);
raf.writeBytes(data);
for(int j=0;j<temp.length()-data.length();j++)
raf.writeBytes(" ");
break;
}
else
overflow++;
}
if(overflow==M) //已經存滿M個點 overflow
{
raf2.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 ); //搜尋區塊
for(int i=0;i<M;i++) //檢查此區塊是否已存M點
{
if((diskcon=raf2.readLine()).equals(temp))
{
raf2.seek(raf2.getFilePointer()-17-N_len);
raf2.writeBytes(data);
for(int j=0;j<temp.length()-data.length();j++)
raf2.writeBytes(" ");
break;
}
}
}
raf.seek(0);
raf2.seek(0);
}
raf.close();
raf2.close();
fr.close();
//成功建立index
while( !(strin.equals("E")) )
{
File file3 = new File("gri.idx");
RandomAccessFile raf3 = new RandomAccessFile(file3, "rw");
File file4 = new File("gri.iof");
RandomAccessFile raf4 = new RandomAccessFile(file4, "rw");
System.out.println("Enter the command: ");
System.out.println("I)nsert ");
System.out.println("D)elete ");
System.out.println("Q)uery");
System.out.println("U)pdate to next time ");
System.out.println("E)xit ");
strin=buf.readLine();
strin=strin.toUpperCase();
String inc;
switch(strin)
{
case "I":
{
System.out.println("Please enter xlow,ylow,xhigh,yhigh");
inc="null,";
inc=inc+buf.readLine();
String result[]=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
count_d=Insert(inc,raf3,raf4,M,result,N_len,temp,count_d);
break;
}
case "D":
{
System.out.println("Please enter ID,xlow,ylow,xhigh,yhigh");
inc=buf.readLine();
String result[]=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
if(result[0].equals("true"))
{
Delete(inc,raf3,raf4,M,result,N_len,temp);
System.out.println("Remove finished");
}
else
System.out.println("It does not exist at this point");
break;
}
case "Q":
{
// System.out.println("please enter ID,xlow,ylow,xhigh,yhigh");
inc=buf.readLine();
String result[]=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
if(result[0].equals("true"))
System.out.println("The presence of this point");
else
System.out.println("It does not exist at this point");
// System.out.println("此點會被歸在cell: ("+result[1]+","+result[2]+") ,會被放在: "+result[3]+" 區");
break;
}
case "U":
{
if(timestamp<100)
{
String source_file="stdout"+Integer.toString(timestamp)+".txt";
timestamp++;
String update_file="stdout"+Integer.toString(timestamp)+".txt";
FileReader fr_s = new FileReader(source_file);
BufferedReader bfr_s = new BufferedReader(fr_s);
FileReader fr_u = new FileReader(update_file);
BufferedReader bfr_u = new BufferedReader(fr_u);
String str_s,str_u;
int temp_ID=1;
int count_fai=0;
while( ( str_s=bfr_s.readLine() )!=null ) //從source讀取 & update
{
String temp2[] = str_s.split(" ");
String everyID=Integer.toString(temp_ID);
temp_ID++;
inc=everyID+","+temp2[1]+","+temp2[2]+","+temp2[3]+","+temp2[4];
String ID[]=inc.split(",");
String result[]=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
// System.out.println(everyID);
if(result[0].equals("true"))
{
Delete(inc,raf3,raf4,M,result,N_len,temp);
str_u=bfr_u.readLine();
String temp3[] = str_u.split(" ");
inc=everyID+","+temp3[1]+","+temp3[2]+","+temp3[3]+","+temp3[4];
result=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
System.out.print("移動結果:");
Insert(inc,raf3,raf4,M,result,N_len,temp,count_d);
}
else
{
str_u=bfr_u.readLine();
count_fai++;
// System.out.pruintln("不存在此點");
}
}
System.out.println("finish");
// System.out.println(count_fai);
}
// System.out.println("請輸入此點的ID,xlow,ylow,xhigh,yhigh");
// inc=buf.readLine();
// String ID[]=inc.split(",");
// String result[]=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
// if(result[0].equals("true"))
// {
// Delete(inc,raf3,raf4,M,result,N_len,temp);
// System.out.println("要移動到? 輸入xlow,ylow,xhigh,yhigh");
// inc=ID[0]+","+buf.readLine();
// result=checkpoint(inc,raf3,raf4,M,grid_i,N_len,temp,cellx,celly,method);
// System.out.print("移動結果:");
// Insert(inc,raf3,raf4,M,result,N_len,temp,count_d);
// }
//
// else
// System.out.println("不存在此點");
break;
}
case "E":
{
System.out.println("exit... thanks .. bye..");
break;
}
}
raf3.close();
raf4.close();
}
}
static int Insert(String P, RandomAccessFile raf, RandomAccessFile raf2,int M, String result[], int N_len, String temp,int count_d) throws IOException
{
int disk_p=Integer.parseInt(result[3]);
String diskcon,data;
String[] P_pos = P.split(",");
raf.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
raf2.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
int overflow=0;
for(int i=0;i<M;i++) //檢查此區塊是否存了M個點
{
if((diskcon=raf.readLine()).equals(temp))
{
if(P_pos[0].equals("null"))
{
count_d++;
data=Integer.toString(count_d)+": "+P_pos[1]+" "+P_pos[2];
}
else
data=P_pos[0]+": "+P_pos[1]+" "+P_pos[2];
raf.seek(raf.getFilePointer()-17-N_len);
raf.writeBytes(data);
for(int j=0;j<temp.length()-data.length();j++)
raf.writeBytes(" ");
System.out.println("成功,"+P_pos[0]+" 在orderfile "+result[3]+"區");
return count_d;
}
else
overflow++;
}
if(overflow==M) //已經存滿M個點 overflow
{
overflow=0;
for(int i=0;i<M;i++)
{
if((diskcon=raf2.readLine()).equals(temp))
{
if(P_pos[0].equals("null"))
{
count_d++;
data=Integer.toString(count_d)+": "+P_pos[1]+" "+P_pos[2];
}
else
data=P_pos[0]+": "+P_pos[1]+" "+P_pos[2];
raf2.seek(raf2.getFilePointer()-17-N_len);
raf2.writeBytes(data);
for(int j=0;j<temp.length()-data.length();j++)
raf2.writeBytes(" ");
System.out.println("成功, 在Overflow "+result[3]+"區");
return count_d;
}
else
overflow++;
}
}
if(overflow==M)
System.out.println("都滿囉,丟掉了");
return count_d;
}
static void Delete(String P, RandomAccessFile raf, RandomAccessFile raf2,int M, String result[], int N_len, String temp) throws IOException
{
int disk_p=Integer.parseInt(result[3]);
String diskcon;
String[] P_pos = P.split(",");
raf.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
raf2.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
P_pos[0]=P_pos[0]+":";
for(int i=0;i<M;i++) //檢查此區塊(orderfile)是否存點
{
diskcon=raf.readLine();
if(!diskcon.equals(temp))
{
String[] pos = diskcon.split(" ");
if(pos[1].equals(P_pos[1]) && pos[2].equals(P_pos[2]) && pos[0].equals(P_pos[0])) //找到了
{
raf.seek(raf.getFilePointer()-17-N_len);
raf.writeBytes(temp);
raf.writeBytes("\r\n");
}
}
}
for(int i=0;i<M;i++) //檢查此區塊(overflow)是否存點
{
diskcon=raf2.readLine();
if(!diskcon.equals(temp))
{
String[] pos = diskcon.split(" ");
if(pos[1].equals(P_pos[1]) && pos[2].equals(P_pos[2]) && pos[0].equals(P_pos[0])) //找到了
{
raf2.seek(raf2.getFilePointer()-17-N_len);
raf2.writeBytes(temp);
raf2.writeBytes("\r\n");
}
}
}
}
static String[] checkpoint(String P, RandomAccessFile raf, RandomAccessFile raf2, int M, int grid_i, int N_len, String temp, double cellx, double celly,int method) throws IOException
{
String result[]={"","","",""};
String diskcon;
String[] P_pos = P.split(",");
int ci=(int) Math.ceil( (Double.parseDouble(P_pos[1])/cellx) );
int cj=(int) Math.ceil( (Double.parseDouble(P_pos[2])/celly) );
int disk_p=(cj-1)*grid_i+ci-1;
if(method==2)
disk_p=cul_zorder(ci,cj);
result[1]=Integer.toString(ci);
result[2]=Integer.toString(cj);
result[3]=Integer.toString(disk_p);
if(P_pos[0].equals("null"))
{
result[0]="null";
return result;
}
P_pos[0]=P_pos[0]+":";
raf.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
raf2.seek( ( N_len+1+2+ (temp.length()+2)*M )*disk_p + N_len+1+2 );
for(int i=0;i<M;i++) //檢查ORDERFILE是否存此點
{
// System.out.println("搜尋orderfile區塊");
diskcon=raf.readLine();
// System.out.println(diskcon);
if(!diskcon.equals(temp))
{
String[] pos = diskcon.split(" ");
if(pos[1].equals(P_pos[1]) && pos[2].equals(P_pos[2]))
{
if(P_pos[0].equals(pos[0]))
{
System.out.println("在orderfile "+result[3]+"區");
result[0]="true"; //return true;
return result;
}
}
}
}
for(int i=0;i<M;i++) //檢查OVERFLOW是否存此點
{
diskcon=raf2.readLine();
// System.out.println(diskcon);
if(!diskcon.equals(temp))
{
String[] pos = diskcon.split(" ");
if(pos[1].equals(P_pos[1]) && pos[2].equals(P_pos[2]))
{
if(P_pos[0].equals(pos[0]))
{
System.out.println("在overflow "+result[3]+"區");
result[0]="true"; //return true;
return result;
}
}
}
}
result[0]="false"; //return false;
return result;
}
static int cul_zorder(int ci,int cj)
{
String b_ci=null,b_cj=null;
int x=ci-1,y=cj-1,disk_p;
if(x==0)
b_ci=b_ci+"0";
if(y==0)
b_cj=b_cj+"0";
while(x>0)
{
b_ci=b_ci+Integer.toString(x%2);
x=x/2;
}
while(y>0)
{
b_cj=b_cj+Integer.toString(y%2);
y=y/2;
}
if(b_ci.length()>b_cj.length())
for(int i=b_ci.length()-b_cj.length();i>0;i--)
b_cj=b_cj+"0";
else if(b_ci.length()<b_cj.length())
for(int i=b_cj.length()-b_ci.length();i>0;i--)
b_ci=b_ci+"0";
String zdisk="nu";
for(int i=b_cj.length()-1;i>=0;i--)
{
if(b_ci.charAt(i)=='0')
zdisk=zdisk+"0";
else if(b_ci.charAt(i)=='1')
zdisk=zdisk+"1";
if(b_cj.charAt(i)=='0')
zdisk=zdisk+"0";
else if(b_cj.charAt(i)=='1')
zdisk=zdisk+"1";
}
int two_d=1,dig=0;
for(int i=zdisk.length()-1;i>=0;i--)
{
if(zdisk.charAt(i)=='1')
dig=dig+two_d;
two_d=two_d*2;
}
disk_p=dig;
return disk_p;
}
}
Related
Display the Shortest Path using BFS in java
This is my BFS algorithm code. I can calculate the shortest path distance, but somehow I am not able to display the shortest path. Like for example, I calculated the shortest path from source to destination is 2. But i would like to also display the pathway. (PlaceA -> PlaceB -> PlaceC) for example. May i know how do i display out the shortest path out using Java? Please do help me! Thank you! public static void main(String[] args) { // TODO Auto-generated method stub chooseNumOfVertices(); chooseNumOfEdges(); generateGraph(); in.close(); } private static void generateGraph() { int source = 0; int destination = 0; int edge = chooseEdge; // TODO Auto-generated method stub ArrayList<LinkedList<Integer>> graph = new ArrayList<LinkedList<Integer>>(); for (int i = 0; i < limit; i++) { LinkedList<Integer> vertex = new LinkedList<Integer>(); vertex.add(i); graph.add(vertex); } while (chooseEdge > 0) { // Randomize the value int value = new Random().nextInt(cityMapping.size()); int value2 = new Random().nextInt(cityMapping.size()); // if (value != value2 && !graph.get(value).contains(value2) && !graph.get(value2).contains(value)) { graph.get(value).add(value2); graph.get(value2).add(value); chooseEdge--; } } // Printing out the Nodes for (int i = 0; i < graph.size(); i++) { // Return each LinkedList nodes // System.out.println(graph.get(i)); for (int j = 0; j < graph.get(i).size(); j++) { // Return each individual nodes inside LinkedList for (Entry<Integer, String> entry : cityMapping.entrySet()) { if (entry.getKey() == graph.get(i).get(j)) { //System.out.print(graph.get(i).get(j) + "-> "); System.out.print(graph.get(i).get(j) + ". " + entry.getValue() + " -> "); } } } System.out.println(); } do { for ( int i = 0; i < limit; i++) { int[] newArray = new int[limit]; distance.add(newArray); predecessor.add(newArray); } long time = System.nanoTime(); System.out.println("Searching BFS"); System.out.println("--------------------------------------------"); for (int i = 0; i < limit; i++) { BFS(graph, i); } long CPUTime = (System.nanoTime() - time); System.out.println("CPU Time for BFS for " + limit + "vertices and " + edge + "edges (in ns): " + CPUTime); System.out.print("Enter -1 to exit! Enter source vertex (between 0 to " + (limit - 1) + ") : "); source = in.nextInt(); if (source == -1) { System.out.print("System terminating..."); break; } System.out.print("Enter destination vertex (between 0 to " + (limit - 1) + ") : "); destination = in.nextInt(); System.out.println("Distance from " + source + " to " + destination + " is: " + getDistance(source, destination)); System.out.println("The Predecessor of the path from " + source + " to " + destination + " is: " + getPredecessor(source, destination)); } while (source != -1); } private static void BFS(ArrayList<LinkedList<Integer>> graph, int i) { // TODO Auto-generated method stub boolean[] mark = new boolean[graph.size()]; Queue<Integer> L = new ArrayBlockingQueue<Integer>(graph.size()); //Queue L.add(i); mark[i] = true; Arrays.fill(predecessor.get(i), -1); Arrays.fill(distance.get(i), -1); distance.get(i)[i] = 0; while (!L.isEmpty()) { int vertex = L.remove(); for (int i1 = 0; i1 < graph.get(vertex).size(); i1++) { int v = graph.get(vertex).get(i1); if (!mark[v]) { mark[v] = true; predecessor.get(i)[v] = vertex; L.add(v); distance.get(i)[v] = distance.get(i)[predecessor.get(i)[v]] + 1; } } } } public static int getDistance(int start, int end) { return (distance.get(start)[end]); } public static int getPredecessor(int start, int end) { return (predecessor.get(start)[end]); } private static void chooseNumOfEdges() { System.out.println("Please input the number of Edges:"); chooseEdge = in.nextInt(); } // Number of Vertices private static void chooseNumOfVertices() { in = new Scanner(System.in); System.out.println("Please input the number of Vertices:"); limit = in.nextInt(); // Read CSV List<String[]> content = readCsvFile(); // Map each number to a city name cityMapping = new HashMap<>(); for (int i = 0; i < limit; i++) { cityMapping.put(i, content.get(i)[0]); } // System.out.println(cityMapping); } // Read CSV file public static List<String[]> readCsvFile() { String csvFile = "./Lab 4/country.csv"; BufferedReader br = null; ArrayList<String> names = new ArrayList<String>(); List<String[]> content = new ArrayList<>(); String cvsSplitBy = ","; try { String line = ""; br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { content.add(line.split(cvsSplitBy)); } } catch (Exception e) { e.printStackTrace(); } Random r = new Random(); Collections.shuffle(content); return content; } }
How to input Strings into a 2D array
I have this code and I need to export the strings 'Name','Testav','HWav','Lows','grade' into a 2D array with the columns being the following respectively. I then need to export the 2D array into a csv file. Any help would be greatly appreciated. import java.util.*; import java.io.*; import java.io.PrintWriter; import java.text.*; public class ComputeGrades { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Please enter the name of the input file: "); String input_name = in.next(); System.out.printf("Please enter the name of the output CSV file: "); String csv_name = in.next(); System.out.printf("Please enter the name of the output pretty-print file: "); String pretty_name = in.next(); processGrades(input_name, csv_name, pretty_name); System.out.printf("\nExiting...\n"); } public static void processGrades (String input_name, String csv_name, String pretty_name) { PrintWriter csv = null; PrintWriter pretty = null; String[][] data = readSpreadsheet(input_name); boolean resultb = sanityCheck(data); int length = data.length; ArrayList<String> test_avg = new ArrayList<String>(); ArrayList<String> HW_avg = new ArrayList<String>(); ArrayList<String> NAME = new ArrayList<String>(); ArrayList<String> ColN = new ArrayList<String>(); ArrayList<String> Hell = new ArrayList<String>(); String[][] kill_me = new String[length][]; for(int row = 1; row<length; row++) { String name = data[row][0]; String name2 = data[row][1]; String Name = name+" "+name2; int test1 = Integer.parseInt(data[row][2]); int test2 = Integer.parseInt(data[row][3]); int test3 = Integer.parseInt(data[row][4]); int Test = (test1+test2+test3)/3; String Testav = Integer.toString(Test); int hw1 = Integer.parseInt(data[row][5]); int hw2 = Integer.parseInt(data[row][6]); int hw3 = Integer.parseInt(data[row][7]); int hw4 = Integer.parseInt(data[row][8]); int hw5 = Integer.parseInt(data[row][9]); int hw6 = Integer.parseInt(data[row][10]); int hw7 = Integer.parseInt(data[row][11]); int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7; String HWav = Integer.toString(HW); int[] trying = {Test, HW}; int low = find_min(trying); String Lows = Integer.toString(low); String grade = null; if(low>=90) { grade ="A"; } if(low < 90 && low>= 80) { grade = "B"; } if(low <80 && low>=70) { grade ="C"; } if(low<70 && low>=60) { grade="D"; } if(low<60) { grade = "F"; } test_avg.add(Testav); HW_avg.add(HWav); NAME.add(Name); Hell.add(Name); Hell.add(Testav); Hell.add(HWav); Hell.add(Lows); Hell.add(grade); } System.out.println(Hell); System.out.printf("\n"); File csvFile = new File(csv_name); try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){ Hell.stream().forEach(csvWriter::println); } catch (IOException e) { } } public static int find_min(int[] values) { int result = values[0]; for(int i = 0; i<values.length; i++) { if(values[i]<result) { result = values[i]; } } return result; } public static boolean sanityCheck(String[][] data) { if (data == null) { System.out.printf("Sanity check: nul data\n"); return false; } if(data.length<3) { System.out.printf("Sanity check: %d rows\n",data.length); return false; } int cols= data[0].length; for(int row = 0; row<data.length; row++) { int current_cols = data[row].length; if(current_cols!=cols) { System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row); return false; } } return true; } public static String[][] readSpreadsheet(String filename) { ArrayList<String> lines = readFile(filename); if (lines == null) { return null; } int rows = lines.size(); String[][] result = new String[rows][]; for (int i = 0; i < rows; i++) { String line = lines.get(i); String[] values = line.split(","); result[i] = values; } return result; } public static ArrayList<String> readFile(String filename) { File temp = new File(filename); Scanner input_file; try { input_file = new Scanner(temp); } catch (Exception e) { System.out.printf("Failed to open file %s\n", filename); return null; } ArrayList<String> result = new ArrayList<String>(); while (input_file.hasNextLine()) { String line = input_file.nextLine(); result.add(line); } input_file.close(); return result; } } input file: First,Last,Exam1,Exam2,Final,H1,H2,H3,H4,H5,H6,H7 Ping,Milledge,43,59,68,69,62,43,60,38,37,40 Elisa,Oltz,76,94,73,100,99,100,90,97,100,92 Leonard,Havers,67,95,57,69,95,71,68,61,93,61 Setsuko,Lovera,78,100,84,89,88,92,65,85,66,97 Franklyn,Degnim,54,74,50,63,78,42,42,41,67,64 Gwyneth,Marsico,61,89,81,59,59,62,88,60,66,66 Abigail,Greep,69,99,93,94,91,85,78,91,69,71 Majorie,Granvold,78,100,100,82,96,100,89,100,100,94 Daphine,Polaco,62,82,88,81,68,89,62,73,90,62 An,Corvera,44,71,37,46,57,42,59,66,54,60 Ayanna,Pensiero,64,42,56,37,53,66,69,52,43,58 Era,Deming,98,81,100,69,65,73,77,78,73,89 Michal,Slentz,73,85,81,82,74,93,81,76,69,81 Corie,Brazen,86,99,66,100,69,97,96,100,70,84 Dona,Tufte,63,54,70,71,55,68,86,66,75,63 Juan,Rohdenburg,78,89,100,91,80,97,92,100,98,100 Orville,Samit,88,63,60,88,81,56,91,76,77,80 Ricky,Knoechel,100,100,93,81,100,90,100,92,100,84 Blythe,Threet,38,68,35,61,63,51,48,72,49,51 Sammie,Wachs,46,53,52,76,50,52,56,68,46,75 Estelle,Veazey,72,87,69,98,96,77,95,91,100,91 Agatha,Keckler,100,92,90,95,85,100,94,85,92,100 Novella,Oros,85,76,100,92,84,77,77,90,86,98 Tanya,Quinlisk,47,78,71,50,79,52,69,66,51,45 Marion,Coltrin,68,68,54,39,61,44,66,58,47,74 Helene,Karow,100,100,75,79,100,100,100,92,89,96 Shonta,Bourek,100,96,90,81,97,84,91,100,100,100 Hyon,Anglemyer,81,76,43,43,47,53,44,60,57,65 Ervin,Kenison,78,53,54,75,55,46,61,75,56,69 Renato,Urch,71,64,64,84,49,57,63,69,81,64 Mikel,Burleigh,88,100,90,100,90,91,90,80,74,74 Val,Royal,100,80,100,99,100,100,76,86,100,96 Jodie,Adolfo,94,77,59,83,67,79,87,82,82,75 Roselee,Lienhard,68,75,58,82,96,62,60,94,68,58 Austin,Holznecht,76,49,79,48,58,68,67,71,70,61 Emelia,Toney,70,95,74,90,99,68,100,66,98,98 Lucy,Rhodd,71,91,100,82,100,93,100,100,71,81 Sacha,Chee,78,71,90,82,74,64,62,87,69,84 Julio,Lackner,56,86,53,88,88,73,57,59,80,85 Salvador,Gretzner,54,83,91,66,78,67,61,84,82,6 export file(csv_name) name,exam_score,hw_score,min_score,grade Ping Milledge,56.666667,49.857143,49.857143,F Elisa Oltz,81.000000,96.857143,81.000000,B Leonard Havers,73.000000,74.000000,73.000000,C Setsuko Lovera,87.333333,83.142857,83.142857,B Franklyn Degnim,59.333333,56.714286,56.714286,F Gwyneth Marsico,77.000000,65.714286,65.714286,D Abigail Greep,87.000000,82.714286,82.714286,B Majorie Granvold,92.666667,94.428571,92.666667,A Daphine Polaco,77.333333,75.000000,75.000000,C An Corvera,50.666667,54.857143,50.666667,F Ayanna Pensiero,54.000000,54.000000,54.000000,F Era Deming,93.000000,74.857143,74.857143,C Michal Slentz,79.666667,79.428571,79.428571,C Corie Brazen,83.666667,88.000000,83.666667,B Dona Tufte,62.333333,69.142857,62.333333,D Juan Rohdenburg,89.000000,94.000000,89.000000,B Orville Samit,70.333333,78.428571,70.333333,C Ricky Knoechel,97.666667,92.428571,92.428571,A Blythe Threet,47.000000,56.428571,47.000000,F Sammie Wachs,50.333333,60.428571,50.333333,F Estelle Veazey,76.000000,92.571429,76.000000,C Agatha Keckler,94.000000,93.000000,93.000000,A Novella Oros,87.000000,86.285714,86.285714,B Tanya Quinlisk,65.333333,58.857143,58.857143,F Marion Coltrin,63.333333,55.571429,55.571429,F Helene Karow,91.666667,93.714286,91.666667,A Shonta Bourek,95.333333,93.285714,93.285714,A Hyon Anglemyer,66.666667,52.714286,52.714286,F Ervin Kenison,61.666667,62.428571,61.666667,D Renato Urch,66.333333,66.714286,66.333333,D Mikel Burleigh,92.666667,85.571429,85.571429,B Val Royal,93.333333,93.857143,93.333333,A Jodie Adolfo,76.666667,79.285714,76.666667,C Roselee Lienhard,67.000000,74.285714,67.000000,D Austin Holznecht,68.000000,63.285714,63.285714,D Emelia Toney,79.666667,88.428571,79.666667,C Lucy Rhodd,87.333333,89.571429,87.333333,B Sacha Chee,79.666667,74.571429,74.571429,C Julio Lackner,65.000000,75.714286,65.000000,D Salvador Gretzner,76.000000,71.714286,71.714286,C export file 2(pretty_name) name: exam score, hw score, min score, grade Ping Milledge: 56.67, 49.86, 49.86, F Elisa Oltz: 81.00, 96.86, 81.00, B Leonard Havers: 73.00, 74.00, 73.00, C Setsuko Lovera: 87.33, 83.14, 83.14, B Franklyn Degnim: 59.33, 56.71, 56.71, F Gwyneth Marsico: 77.00, 65.71, 65.71, D Abigail Greep: 87.00, 82.71, 82.71, B Majorie Granvold: 92.67, 94.43, 92.67, A Daphine Polaco: 77.33, 75.00, 75.00, C An Corvera: 50.67, 54.86, 50.67, F Ayanna Pensiero: 54.00, 54.00, 54.00, F Era Deming: 93.00, 74.86, 74.86, C Michal Slentz: 79.67, 79.43, 79.43, C Corie Brazen: 83.67, 88.00, 83.67, B Dona Tufte: 62.33, 69.14, 62.33, D Juan Rohdenburg: 89.00, 94.00, 89.00, B Orville Samit: 70.33, 78.43, 70.33, C Ricky Knoechel: 97.67, 92.43, 92.43, A Blythe Threet: 47.00, 56.43, 47.00, F Sammie Wachs: 50.33, 60.43, 50.33, F Estelle Veazey: 76.00, 92.57, 76.00, C Agatha Keckler: 94.00, 93.00, 93.00, A Novella Oros: 87.00, 86.29, 86.29, B Tanya Quinlisk: 65.33, 58.86, 58.86, F Marion Coltrin: 63.33, 55.57, 55.57, F Helene Karow: 91.67, 93.71, 91.67, A Shonta Bourek: 95.33, 93.29, 93.29, A Hyon Anglemyer: 66.67, 52.71, 52.71, F Ervin Kenison: 61.67, 62.43, 61.67, D Renato Urch: 66.33, 66.71, 66.33, D Mikel Burleigh: 92.67, 85.57, 85.57, B Val Royal: 93.33, 93.86, 93.33, A Jodie Adolfo: 76.67, 79.29, 76.67, C Roselee Lienhard: 67.00, 74.29, 67.00, D Austin Holznecht: 68.00, 63.29, 63.29, D Emelia Toney: 79.67, 88.43, 79.67, C Lucy Rhodd: 87.33, 89.57, 87.33, B Sacha Chee: 79.67, 74.57, 74.57, C Julio Lackner: 65.00, 75.71, 65.00, D Salvador Gretzner: 76.00, 71.71, 71.71, C
This should do it, if you have question about the code, just ask. public static void processGrades (String input_name, String csv_name, String pretty_name) { DecimalFormat decimalFormat = new DecimalFormat(".000000"); String[][] data = readSpreadsheet(input_name); String[][] result = new String[data.length][]; result[0] = new String[]{"name", "exam_score", "hw_score", "min_score", "grade"}; // Export to 2D String array for(int row = 1; row < data.length; row++) { String name = data[row][0] + " " + data[row][1]; double testAverage = average(data[row], 2, 5); double homeworkAverage = average(data[row], 5, 12); double min = Math.min(testAverage, homeworkAverage); char grade = (char) (74 - ((int) min / 10)); grade = grade > 'D' ? 'F' : grade; result[row] = new String[]{ name, decimalFormat.format(testAverage), decimalFormat.format(homeworkAverage), decimalFormat.format(min), Character.toString(grade) }; } // Export 2D array into a csv String String csv = ""; for (int y = 0; y < result.length; y++) { for (int x = 0; x < result[y].length - 1; x++) { csv += result[y][x] + ","; } csv += result[y][result[y].length - 1] + "\n"; } // Save String in file File file = new File(csv_name); try { BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); bw.write(csv); bw.close(); } catch (IOException e) { e.printStackTrace(); } } private static double average(String[] row, int fromIndex, int toIndex) { double total = 0; for (int i = fromIndex; i < toIndex; i++) { total += Integer.parseInt(row[i]); } return total / (toIndex - fromIndex); }
Java program to count lines, words, and chars from a text given file
I am practicing to write a program that gets a text file from user and provides data such as characters, words, and lines in the text. I have searched and looked over the same topic but cannot find a way to make my code run. public class Document{ private Scanner sc; // Sets users input to a file name public Document(String documentName) throws FileNotFoundException { File inputFile = new File(documentName); try { sc = new Scanner(inputFile); } catch (IOException exception) { System.out.println("File does not exists"); } } public int getChar() { int Char= 0; while (sc.hasNextLine()) { String line = sc.nextLine(); Char += line.length() + 1; } return Char; } // Gets the number of words in a text public int getWords() { int Words = 0; while (sc.hasNext()) { String line = sc.next(); Words += new StringTokenizer(line, " ,").countTokens(); } return Words; } public int getLines() { int Lines= 0; while (sc.hasNextLine()) { Lines++; } return Lines; } } Main method: public class Main { public static void main(String[] args) throws FileNotFoundException { DocStats doc = new DocStats("someText.txt"); // outputs 1451, should be 1450 System.out.println("Number of characters: " + doc.getChar()); // outputs 0, should be 257 System.out.println("Number of words: " + doc.getWords()); // outputs 0, should be 49 System.out.println("Number of lines: " + doc.getLines()); } } I know exactly why I get 1451 instead of 1451. The reason is because I do not have '\n' at the end of the last sentence but my method adds numChars += line.length() + 1; However, I cannot find a solution to why I get 0 for words and lines. *My texts includes elements as: ? , - ' After all, could anyone help me to make this work? **So far, I the problem that concerns me is how I can get a number of characters, if the last sentence does not have '\n' element. Is there a chance I could fix that with an if statement? -Thank you!
After doc.getChar() you have reached the end of file. So there's nothing more to read in this file! You should reset your scanner in your getChar/Words/Lines methods, such as: public int getChar() { sc = new Scanner(inputFile); ... // solving your problem with the last '\n' while (sc.hasNextLine()) { String line = sc.nextLine(); if (sc.hasNextLine()) Char += line.length() + 1; else Char += line.length(); } return char; } Please note that a line ending is not always \n! It might also be \r\n (especially under windows)! public int getWords() { sc = new Scanner(inputFile); ... public int getLines() { sc = new Scanner(inputFile); ...
I would use one sweep to calculate all 3, with different counters. just a loop over each char, check if its a new word etc, increase counts , use Charater.isWhiteSpace * import java.io.*; /**Cound lines, characters and words Assumes all non white space are words so even () is a word*/ public class ChrCounts{ String data; int chrCnt; int lineCnt; int wordCnt; public static void main(String args[]){ ChrCounts c = new ChrCounts(); try{ InputStream data = null; if(args == null || args.length < 1){ data = new ByteArrayInputStream("quick brown foxes\n\r new toy\'s a fun game.\nblah blah.la la ga-ma".getBytes("utf-8")); }else{ data = new BufferedInputStream( new FileInputStream(args[0])); } c.process(data); c.print(); }catch(Exception e){ System.out.println("ee " + e); e.printStackTrace(); } } public void print(){ System.out.println("line cnt " + lineCnt + "\nword cnt " + wordCnt + "\n chrs " + chrCnt); } public void process(InputStream data) throws Exception{ int chrCnt = 0; int lineCnt = 0; int wordCnt = 0; boolean inWord = false; boolean inNewline = false; //char prev = ' '; while(data.available() > 0){ int j = data.read(); if(j < 0)break; chrCnt++; final char c = (char)j; //prev = c; if(c == '\n' || c == '\r'){ chrCnt--;//some editors do not count line seperators as new lines inWord = false; if(!inNewline){ inNewline = true; lineCnt++; }else{ //chrCnt--;//some editors dont count adjaccent line seps as characters } }else{ inNewline = false; if(Character.isWhitespace(c)){ inWord = false; }else{ if(!inWord){ inWord = true; wordCnt++; } } } } //we had some data and last char was not in new line, count last line if(chrCnt > 0 && !inNewline){ lineCnt++; } this.chrCnt = chrCnt; this.lineCnt = lineCnt; this.wordCnt = wordCnt; } }
Java Serialization issues
I have this code that writes an object: FileOutputStream fileOut = new FileOutputStream("Model.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); And this code that loads the object: Model m = null; try { FileInputStream fileIn = new FileInputStream("Model.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); m = (Model) in.readObject(); in.close(); fileIn.close(); } catch (Exception e) {} setStudentList(m.getStudentList()); setModuleList(m.getModuleList()); I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list. Full source code: import java.io.*; import java.util.*; public class Model implements java.io.Serializable { private Student[] studentList = new Student[0]; private Module[] moduleList = new Module[0]; public void menu() { while (true) { System.out.println ("MENU"); System.out.println (""); System.out.println (" 1 - Run Tests"); System.out.println (" 2 - Add Student"); System.out.println (" 3 - Add Module"); System.out.println (" 4 - Add Student To Module"); System.out.println (" 5 - Save System (Text file)"); System.out.println (" 6 - Load System (Text file)"); System.out.println (" 7 - Save System (Serialized)"); System.out.println (" 8 - Load System (Serialized)"); System.out.println (" 9 - Print Report"); System.out.println (""); System.out.print ("Enter choice: "); String input = keyboard.readString(); switch (input) { case "1" : runTests(); break; case "2" : System.out.print("First Name : "); String fN = keyboard.readString(); System.out.print("Surname : "); String sN = keyboard.readString(); System.out.print("Course Code : "); String c = keyboard.readString(); System.out.print("User ID : "); String iD = keyboard.readString(); AddStudent(iD, sN, fN, c); break; case "3" : System.out.print("Module Code : "); String code = keyboard.readString(); String[] temp = new String[0]; AddModule(code,temp); break; case "4" : System.out.print("Module Code : "); code = keyboard.readString(); Module m = findAModule(code); if (m != null) { System.out.print("User ID : "); iD = keyboard.readString(); Student s = findAStudent(iD); if (s != null) { m.addThisStudent(s); } else { System.out.println("Student not found"); } } else { System.out.println("Module not found"); } break; case "5" : saveToTextFiles(); break; case "6" : loadFromTextFiles(); break; case "7" : saveSerialized(); break; case "8" : break; case "9" : printReport(); break; } } } public void runTests() { loadFromTextFiles(); saveSerialized(); printReport(); } public void loadFromTextFiles() { studentList = new Student[0]; moduleList = new Module[0]; try { Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt"))); int num = fileReader.nextInt(); fileReader.nextLine(); for (int i = 0; i < num; i++) { String u = fileReader.nextLine(); String sn = fileReader.nextLine(); String fn = fileReader.nextLine(); String c = fileReader.nextLine(); AddStudent(u, sn, fn, c); } fileReader.close(); fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt"))); num = fileReader.nextInt(); fileReader.nextLine(); for (int i = 0; i < num; i++) { String code = fileReader.nextLine(); int numOfStudents = fileReader.nextInt(); fileReader.nextLine(); String[] students = new String[numOfStudents]; for (int j = 0; j < numOfStudents; j++) { students[j] = fileReader.nextLine(); } AddModule(code, students); } fileReader.close(); } catch (IOException e) {} } public void saveToTextFiles () { try { PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt"))); outfile.println(studentList.length); for (int i = 0; i < studentList.length; i++) { outfile.println(studentList[i].getUID()); outfile.println(studentList[i].getSN()); outfile.println(studentList[i].getFN()); outfile.println(studentList[i].getDegree()); } outfile.close(); outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt"))); outfile.println(moduleList.length); for (int i = 0; i < moduleList.length; i++) { outfile.println(moduleList[i].getCode()); outfile.println(moduleList[i].getStudents().length); for (int j = 0; j < moduleList[i].getStudents().length; j++) { outfile.println(moduleList[i].getStudents()[j]); } } outfile.close(); } catch (IOException e) {} } public void saveSerialized() { try { FileOutputStream fileOut = new FileOutputStream("Model.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); FileOutputStream fileOut2 = new FileOutputStream("Module.ser"); ObjectOutputStream out2 = new ObjectOutputStream(fileOut2); out2.writeObject(studentList); out2.close(); fileOut2.close(); FileOutputStream fileOut3 = new FileOutputStream("Student.ser"); ObjectOutputStream out3 = new ObjectOutputStream(fileOut3); out3.writeObject(moduleList); out3.close(); fileOut3.close(); } catch (IOException e) {} } public void loadSerialized() { Model m = null; try { FileInputStream fileIn = new FileInputStream("Model.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); m = (Model) in.readObject(); in.close(); fileIn.close(); } catch (Exception e) {} setStudentList(m.getStudentList()); setModuleList(m.getModuleList()); } private Module[] getModuleList() { return moduleList; } private Student[] getStudentList() { return studentList; } private void setModuleList(Module[] m) { moduleList = m.clone(); } private void setStudentList(Student[] s) { studentList = s.clone(); } private void AddModule(String code, String[] students) { int length = moduleList.length; Module NewArray[] = new Module[length + 1]; for (int i = 0; i < length + 1; i++) { if (i < length) { NewArray[i] = new Module(moduleList[i]); } } NewArray[length] = new Module(code, students); moduleList = NewArray.clone(); } private void AddStudent(String u, String sn, String fn, String c) { int length = studentList.length; Student NewArray[] = new Student[length + 1]; for(int i = 0; i < length + 1; i++) { if (i < length) { NewArray[i] = new Student(studentList[i]); } } NewArray[length] = new Student(u, sn, fn, c); studentList = NewArray.clone(); } public void printReport() { for (int i = 0; i < moduleList.length; i++) { System.out.println(moduleList[i].toString(this)); } } public Student findAStudent(String uid) { for (int i = 0; i < studentList.length; i++) { if (studentList[i].getUID().compareTo(uid) == 0) { return studentList[i]; } } return null; } public Module findAModule(String code) { for (int i = 0; i < moduleList.length; i++) { if (moduleList[i].getCode().compareTo(code) == 0) { return moduleList[i]; } } return null; } }
Look at your code sample, in particular the switch statement: switch (input) { ... case "8" : break; ... } I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code. Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module. Edit: why using serialization to persist objects is a bad idea In simple terms, using serialization to persist objects is brittle. An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new. While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system. There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.
Exception in thread "main" java.lang.NullPointerException when trying to update file
I'm in a beginner CS class and I'm trying to update info in a file. The info in the array does get replaced temporarily; however, I am unable to save the changes to the file. And, even after it's replaced, I get the "null" error. Here is my code, I have omitted the lines and methods that are unrelated: public static void readData(){ // Variables int choice2, location; // Read file File dataFile = new File("C:/Users/shirley/Documents/cddata.txt"); FileReader in; BufferedReader readFile; // Arrays String[] code = new String[100]; String[] type = new String[100]; String[] artist = new String[100]; String[] song = new String[100]; Double[] price = new Double[100]; Double[] vSales = new Double[100]; // Split Variables String tempCode, tempType, tempArtist, tempSong, tempPrice, tempVsales; // Split String text; int c = 0; try{ in = new FileReader(dataFile); readFile = new BufferedReader(in); while ((text = readFile.readLine()) != null){ // Split line into temp variables tempCode = text.substring(0,5); tempType = text.substring(5,15); tempArtist = text.substring(16,30); tempSong = text.substring(30,46); tempPrice = text.substring(46,52); tempVsales = text.substring(52); // Place text in correct arrays code[c] = tempCode; type[c] = tempType; artist[c] = tempArtist; song[c] = tempSong; price[c] = Double.parseDouble(tempPrice); vSales[c] = Double.parseDouble(tempVsales); c += 1; // increase counter } // Output to user Scanner kb = new Scanner(System.in); System.out.print("\nSelect another number: "); choice2 = kb.nextInt(); // Reads data if (choice2 == 5){ reqStatsSort(code,type,artist,song,price,vSales,c); location = reqStatistics(code,type,artist,song,price,vSales,c); if (location == -1){ System.out.println("Sorry, code not found."); } else{ System.out.print("Enter new volume sales: "); vSales[location] = kb.nextDouble(); } displayBestSellerArray(type,artist,song,vSales,c); readFile.close(); in.close(); changeVolume(code,type,artist,song,price,vSales,c); // Method to rewrite file readData(); } }catch(FileNotFoundException e){ System.out.println("File does not exist or could not be found."); System.err.println("FileNotFoundException: " + e.getMessage()); }catch(IOException e){ System.out.println("Problem reading file."); System.err.println("IOException: " + e.getMessage()); } } ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////// ///////////////// REQ STATS SORT METHOD //////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// public static void reqStatsSort(String[] sortCode, String[] sortType, String[] sortArtist, String[] sortSong, Double[] sortPrice, Double[] sortVSales, int c){ // Variables String tempCode, tempArtist, tempType, tempSong; double tempVsales, tempPrice; for(int j = 0; j < (c - 1); j++){ for (int k = j + 1; k < c; k++){ if ((sortCode[k]).compareToIgnoreCase(sortCode[j]) < 0){ // Switch CODE tempCode = sortCode[k]; sortCode[k] = sortCode[j]; sortCode[j] = tempCode; // Switch TYPE tempType = sortType[k]; sortType[k] = sortType[j]; sortType[j] = tempType; // Switch ARTIST tempArtist = sortArtist[k]; sortArtist[k] = sortArtist[j]; sortArtist[j] = tempArtist; // Switch SONG tempSong = sortSong[k]; sortSong[k] = sortSong[j]; sortSong[j] = tempSong; // Switch VOLUME tempVsales = sortVSales[k]; sortVSales[k] = sortVSales[j]; sortVSales[j] = tempVsales; // Switch PRICE tempPrice = sortPrice[k]; sortPrice[k] = sortPrice[j]; sortPrice[j] = tempPrice; } } } } ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////// /////////////// REQUEST STATISTICS METHOD ////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// public static int reqStatistics(String[] statsCode, String[] statsType, String[] statsArtist, String[] statsSong, Double[] statsPrice, Double[] statsVSales, int c){ // Variables String cdCode; // Obtain input from user Scanner kb = new Scanner(System.in); System.out.print("Enter a CD code: "); cdCode = kb.nextLine(); // Binary search int position; int lowerbound = 0; int upperbound = c - 1; // Find middle position position = (lowerbound + upperbound) / 2; while((statsCode[position].compareToIgnoreCase(cdCode) != 0) && (lowerbound <= upperbound)){ if((statsCode[position].compareToIgnoreCase(cdCode) > 0)){ upperbound = position - 1; } else { lowerbound = position + 1; } position = (lowerbound + upperbound) / 2; } if (lowerbound <= upperbound){ return(position); } else { return (-1); } } ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////// /////////////// BEST SELLER ARRAY METHOD ////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// public static void displayBestSellerArray (String[] displaySortedType, String[] displaySortedArtist, String[] displaySortedSong, Double[] displaySortedVSales, int c){ // Output to user System.out.println(); System.out.println("MUSIC ARTIST HIT SONG VOLUME"); System.out.println("TYPE SALES"); System.out.println("--------------------------------------------------------------------"); for (int i = 0; i < c; i++){ System.out.print(displaySortedType[i] + " " + displaySortedArtist[i] + " " + displaySortedSong[i] + " "); System.out.format("%6.0f",displaySortedVSales[i]); System.out.println(); } } ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// //////////////////////////////////////////////////////// ////////////////// CHANGE VOLUME METHOD //////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// /////////////////////////////////////////////////////// public static void changeVolume(String[] writeCode, String[] writeType, String[] writeArtist, String[] writeSong, Double[] writePrice, Double[] writeVSales, int c){ File textFile = new File("C:/Users/shirley/Documents/cddata.txt"); FileWriter out; BufferedWriter writeFile; // Variables String entireRecord, tempVSales; int decLoc; try{ out = new FileWriter(textFile); writeFile = new BufferedWriter(out); // Output to user for (int i = 1; i <= c; i++){ // Convert volume sales to String tempVSales = Double.toString(writeVSales[i]); // Get rid of decimals decLoc = (tempVSales.indexOf(".")); tempVSales = tempVSales.substring(0,decLoc); // Create record line entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i] + " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales; // Write record to file writeFile.write(entireRecord); if (i != c){ writeFile.newLine(); } } writeFile.close(); out.close(); System.out.println("Data written to file."); } catch(IOException e){ System.out.println("Problem writing to file."); System.out.println("IOException: " + e.getMessage()); } } The last method, changeVolume(), is what isn't working. The error I get is Exception in thread "main" java.lang.NullPointerException at culminating3.Culminating3.changeVolume(Culminating3.java:508) at culminating3.Culminating3.readData(Culminating3.java:185) at culminating3.Culminating3.readData(Culminating3.java:167) at culminating3.Culminating3.main(Culminating3.java:47) Java Result: 1 Line 508 is: tempVSales = Double.toString(writeVSales[i]); in the changeVolume method(). So my program asks the user for a CD code to change the volume of sales, and sorts the arrays to perform a binary search if the inputted code exists. If it does, my program replaces the old volume of sales (which it does), and saves it with the changeVolume() method (which it doesn't do and gives me the error). Please keep in mind I'm a newbie. It looks fine to me but I can't figure out why it's not working. I apologize for any messes in the code. writeVSales[] shouldn't be null because I assigned input in the readData() method?
Problem is here: // Convert volume sales to String tempVSales = Double.toString(writeVSales[i]); // Get rid of decimals decLoc = (tempVSales.indexOf(".")); tempVSales = tempVSales.substring(0,decLoc); I suggest you to take some sample values and work on this first. You can use StringTokenizer to perform this.
When you input the information into the writeVSales array you start at 0 (good) and increment c everytime a new item is added, whether or not there is a new item to add or not (again this is fine). int c = 0; try{ in = new FileReader(dataFile); readFile = new BufferedReader(in); while ((text = readFile.readLine()) != null){ // Split line into temp variables tempCode = text.substring(0,5); tempType = text.substring(5,15); tempArtist = text.substring(16,30); tempSong = text.substring(30,46); tempPrice = text.substring(46,52); tempVsales = text.substring(52); // Place text in correct arrays code[c] = tempCode; type[c] = tempType; artist[c] = tempArtist; song[c] = tempSong; price[c] = Double.parseDouble(tempPrice); vSales[c] = Double.parseDouble(tempVsales); c += 1; // increase counter } Later in changeVolume() your for loop starts at 1 and goes to c. So you are missing the first element and trying to add an element from an index that is null, hence the `NullPointerexception. // Output to user for (int i = 1; i <= c; i++){ //code } Change the for loop to start and 0 and go to i < c (i.e. c - 1): for (int i = 0; i < c; i++){ // Convert volume sales to String tempVSales = Double.toString(writeVSales[i]); // Get rid of decimals decLoc = (tempVSales.indexOf(".")); tempVSales = tempVSales.substring(0,decLoc); // Create record line entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i] + " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales; // Write record to file writeFile.write(entireRecord); if (i != c){ writeFile.newLine(); } }