i wrote this code but its going to fail on 1gb size file.
public class TestFiles {
public static void main(String[] args) {
int minLength = Integer.MAX_VALUE;
int maxLength = Integer.MIN_VALUE;
String minWord = "";
String maxWord = "";
List<String> words = new ArrayList<>();
try {
File myObj = new File("C:\\Users\\Downloads\\java.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
String[] dataArray = data.split(" ");
List<String> list = Arrays.asList(dataArray);
for (String s : list) {
if (s.length() < minLength) {
minLength = s.length();
minWord = s;
} else if (s.length() > maxLength) {
maxLength = s.length();
maxWord = s;
}
}
}
myReader.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("min length " + minLength + " - max lenth " + maxLength);
System.out.println("min length word " + minWord + " - max lenth word " + maxLength);
}
}
could you please answers? how can i solve this?
The problem gets obvious, when 1gb words are squashed into 1 line!*
Solution: Not to process the input "line-wise", but "word-wise", which is suf- & efficient! ;)
Voila:
public class TestFiles {
public static void main(String[] args) {
int minLength = Integer.MAX_VALUE;
int maxLength = Integer.MIN_VALUE;
String minWord = "";
String maxWord = "";
try {
File myObj = new File("C:\\Users\\Downloads\\java.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext()) {
String word = myReader.next();
if (word.length() < minLength) {
minLength = word.length();
minWord = word;
}
if (word.length() > maxLength) {
maxLength = word.length();
maxWord = word;
}
}
}
myReader.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("min length " + minLength + " - max lenth " + maxLength);
System.out.println("min length word " + minWord + " - max lenth word " + maxLength);
}
}
*when "many" words are in one line, then we could get problems here:
myReader.hasNextLine(),
String data = myReader.nextLine() and
String[] dataArray = data.split(" ");
#huy's answer also correct: the else is "efficient for most cases", but is "incorrect for corner cases".
int len = s.length();
if (len < minLength) {
minLength = len;
minWord = s;
}
if (len > maxLength) {
maxLength = len;
maxWord = s;
}
Your test case will fail if large string is located at first index of first line.
Btw, I think you should break your big test to small test, try to find small string and large string for single line, after that multi lines and data from files
Im trying to read a file full of coordinates and then putting everything into double 2 dimensional array. When i run the code i get the exception error. Been trying to read the file for hours now(im a noobie in java)
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
String[] line= new String[rwn];
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
Your code confused me a bit.
But you can try this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
// Define sample data
String coord = ""
+ "0 90 -4228\n"
+ "0.166666666667 90 -4228\n"
+ "0.333333333333 90 -4228\n"
+ "0.5 90 -4228\n"
+ "0.666666666667 90 -4228";
Scanner input = new Scanner(coord);
int rwn = 0;
// Define a 'arrayOfEarth' as list
ArrayList<Double[]> arrayOfEarth = new ArrayList<>();
while (input.hasNextLine()) {
++rwn;
String[] line = input.nextLine().split(" ");
if (line.length == 0) {
continue;
}
arrayOfEarth.add(parseLine(line, rwn));
}
arrayOfEarth.stream()
.forEach(v -> System.out.println(Arrays.toString(v) + "\n"));
}
private static Double[] parseLine(String[] line, int row) {
if (line.length != 3) {
throw new IllegalArgumentException("Missing valiues in line " + row);
}
Double[] doubles = new Double[3];
for (int i = 0; i < 3; i++) {
try {
doubles[i] = Double.parseDouble(line[i]);
} catch (NumberFormatException e) {
throw new NumberFormatException("NAN in " + row + "/" + i + ". value: " + line[i]);
}
}
return doubles;
}
}
This is not 'clean' code - only an example.
I have used the Stream-API. If you use a Java Version < 8 you have to rewrite it with a traditional for-loop.
Scanner input = new Scanner(new File(filename));
int row=0;
int col=0;
int rwn=0;
//String[] line= new String[rwn]; you created line with zero length;
while(input.hasNextLine()) {
line = input.nextLine().split(" ");//spliting 1
rwn++;
}
String[] line= new String[rwn];
double[][] arrayOfEarth = new double[rwn][];//creating array for pairs
//itterating array ^ of splitting 1
for (int i=0;i<rwn;i++){
String[] ln =line[i].split(",");
double a= Double.parseDouble(ln[0]);
double b=Double.parseDouble(ln[1]);
double[] val={a,b};//adding the a and b doubles out of string to the value
arrayOfEarth[i]=val;//add arr to arr of arr
}
for (double[] c:arrayOfEarth){
System.out.println(String.format("%.0f and %.2f",c[0],c[1]));
}
}
catch (Exception e) {
System.out.println("Error bruh: "); e.printStackTrace();
}```
String[] line= new String[rwn]; has to be under while statement. you created line with 0 length
* *
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;
}
}
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();
}
}