csv file and manipulation - java

S.M.Tido,112,145,124
P.julio,178,145,133
Carey,92,100,123
Elain,87,92,92
Theodore,178,155,167
I have read above text file, and tried to find the average values of the 3 readings in every row. But I can only find the average of a single column,because my for loop logic did not work. Can anyone show me how to find the average of every row ?
import java.util.Scanner;
import java.io.*;
public class PatientDetails{
public static void main(String[] args){
String fileName = "patient.txt";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while(inputStream.hasNext()){
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
}
inputStream.close();
System.out.println("Average = "+sum/noOfReadings);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
Note:
Note : I have not learnt data structures in Java so I cannot use lists
In my code.

Just move you println() into the loop, and after that, change the sum back to 0.
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
System.out.println("Average = " + sum / noOfReadings);
sum = 0;
}
inputStream.close();

Related

When I run my code I get (0, null) and cant figure out why

I am creating a program that is reading a file of names and ages then printing them out in ascending order. I am parsing through the file to figure out the number of name age pairs and then making my array that big.
The input file looks like this:
(23, Matt)(2000, jack)(50, Sal)(47, Mark)(23, Will)(83200, Andrew)(23, Lee)(47, Andy)(47, Sam)(150, Dayton)
When I am running my code I get the output of (0,null) and I am not sure why. I have been trying to fix it for a while and am lost. If anyone can help that would be great My code is below.
public class ponySort {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
int fileSize = 0;
int[] ages;
String [] names;
String filename = "";
Scanner inputFile = new Scanner(System.in);
File file;
do {
System.out.println("File to read from:");
filename = inputFile.nextLine();
file = new File(filename);
//inputFile = new Scanner(file);
}
while (!file.exists());
inputFile = new Scanner(file);
if (!inputFile.hasNextLine()) {
System.out.println("No one is going to the Friendship is magic Party in Equestria.");
}
while (inputFile.hasNextLine()) {
String data1 = inputFile.nextLine();
String[] parts1 = data1.split("(?<=\\))(?=\\()");
for (String part : parts1) {
String input1 = part.replaceAll("[()]", "");
Integer.parseInt(input1.split(", ")[0]);
fileSize++;
}
}
ages = new int[fileSize];
names = new String[fileSize];
while (inputFile.hasNextLine()) {
String data = inputFile.nextLine();
String[] parts = data.split("(?<=\\))(?=\\()");
for (String part : parts) {
String input = part.replaceAll("[()]", "");
ages[count] = Integer.parseInt(input.split(", ")[0]);
names[count] = input.split(", ")[1];
count++;
}
}
ponySort max = new ponySort();
max.bubbleSort(ages, names, count);
max.printArray(ages, names, count);
}
public void printArray(int ages[], String names[], int count) {
System.out.print("(" + ages[0] + "," + names[0] + ")");
// Checking for duplicates in ages. if it is the same ages as one that already was put in them it wont print.
for (int i = 1; i < count; i++) {
if (ages[i] != ages[i - 1]) {
System.out.print("(" + ages[i] + "," + names[i] + ")");
}
}
}
public void bubbleSort(int ages[], String names[], int count ){
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
// age is greater so swaps age
if (ages[j] > ages[j + 1]) {
// swap the ages
int temp = ages[j];
ages[j] = ages[j + 1];
ages[j + 1] = temp;
// must also swap the names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;
}
}
}
}
}
output example
File to read from:
file.txt
(0,null)
Process finished with exit code 0
What your code does is to Scan the file twice.
In the first loop you do
String data1 = inputFile.nextLine();
Code reads first line and then scanner goes to the next (second) line.
Later you do again inputFile.nextLine(); The second line is empty and the code never goes into the second loop and content is never read.
If you can use Lists, you should create two array lists and add ages and names into the arraylists in the first scan, so you scan the file once. When done, you could get the Array out of the arraylist.
If you should only use arrays and you want a simple update, just add another Scanner before the second loop:
ages = new int[fileSize];
names = new String[fileSize];
inputFile = new Scanner(file); // add this line

Reading & Breaking CSV File in Java:

I am editing this question to be more specific and I've learned some Jave to find the solution to my problem. I have a file in CSV format like this:
or in excel like this:
Now I am using Java program to read the second line of file and separate each Comma Separated Value and write it to console as well as on other output file and it was done easily. Now I'm trying to break the last value of:
S/1,M/1,L/1,XL/1 | 2XL/1,3XL/1,4XL/1,5XL/1 | MT/1,LT/1 (Original)
S/1,M/1,L/1,XL/1,2XL/1,3XL/1,4XL/1,5XL/1,MT/1,LT/1 (Modified using program to remove spaces and replacing the Pipes (|) with comma.
In each value, There is the size name before Forward Slash (/) and its quantity is after that. What I'm trying is using the Forward Slash (/) to separate the size with its quantity. And the problem is that the size may contain the forward slash as well (e.g. 12/BT or 2BT/2x). I've tried many algorithms like reversing the whole array or storing the slash count but not getting the success. The whole code to read file and break the comma separated values into separate columns of file is as following:
import java.io.*;
import javax.swing.*;
public class ReadFile3c{
public static void main(String args[]){
try{
//Getting File Name
String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
//Creating Stream with File
FileReader fr = new FileReader(fileName);
//Applying Buffer Filter
BufferedReader br = new BufferedReader(fr);
//Reading First line then Second Line
String s = br.readLine();
s = br.readLine();
s = s + ",";//adding comma at the end of the file
s = s.replaceAll("\\s",""); //Eliminating Spaces
s = s.replaceAll("\\|",","); //Replacing Pipes with comma
char charArray[] = s.toCharArray();
//Declaring Strings and variablse for value separating function
int n = 0; //Array Variable
int m = 0; //Array Variable
String[] inverted = new String[3]; //String to store inverted Commas Values
String[] comma = new String[10]; //String to store comma Values
String value = ""; //Storing character values
try{
//Loop to cycle each character of file
for(int j = 0; j<charArray.length;j++){
//Inverted comma value separator
if (charArray[j] == '"') {
j++;
//loop to gather values b/w invreted comma
while((charArray[j] != '"')){
value = value + charArray[j];
j++;
}
inverted[n] = value;
n++;
j++;
value = "";
}else{
j = j - 1;
//comma Value separator
if (charArray[j] == ','){
j++;
//loop to gether values b/w commas
while((charArray[j] !=',')){
value = value + charArray[j];
j++;
}
comma[m] = value;
m++;
value = "";
}
}
}
}catch(Exception ex){
System.out.println("in inner Exception Block" + ex);
}
//declaring variables to storing values
String name, patternCode, placeSizeQty,width,length,utill,pArea,pPerimeter,totalPcs,placePcs,tSizes;
name = inverted[0];
patternCode = inverted[1];
placeSizeQty = inverted[2];
width = comma[0];
length = comma[1];
utill = comma[2];
pArea = comma[3];
pPerimeter = comma[4];
totalPcs = comma[5];
placePcs = comma[6];
tSizes = comma[7];
//printing all values on Console
System.out.println("\nMarkerName: " + name);
System.out.println("Width :" + width);
System.out.println("Length :" + length);
System.out.println("Utill :" + utill);
System.out.println("Place Area :" + pArea);
System.out.println("Place Perimeter :" + pPerimeter);
System.out.println("PatternCode: " + patternCode);
System.out.println("PlaceSizeQty: " + placeSizeQty);
System.out.println("Total Pcs :" + totalPcs);
System.out.println("Place Pcs :" + placePcs);
System.out.println("Total Sizes :" + tSizes);
//Creating Output file
String fileOutput = JOptionPane.showInputDialog("Enter Output File Name") + ".txt";
//File Writer
try{
//Creating Stream with output file
FileWriter fw = new FileWriter(fileOutput);
//Applying Buffring Stream
PrintWriter pw = new PrintWriter(fw);
//Declaration
String outputLine = null;
//Writing Inverted inputs
for (int u = 0; u <=2 ;u++ ) {
outputLine = inverted[u];
pw.println(outputLine);
System.out.println("Writing: " + outputLine);
}//end of for
//writing comma inputs
for (int t = 0;t <=7 ; t++ ) {
outputLine = comma[t];
pw.println(outputLine);
System.out.println("Writing: " + outputLine);
}//end of for
pw.flush();
pw.close();
fw.close();
fr.close();
br.close();
}catch(Exception ex){
System.out.println("Output: " + ex);
}//End of output catch
}catch(IOException ex){
System.out.println(ex);
}//end of catch
}//end of catch
}//end of Class
And the code to Break the Size and quantity and store it in Double array (Not completed) is as Following:
import java.io.*;
import javax.swing.*;
public class ReadFileInvert{
public static void main(String args[]){
try{
String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
System.out.println(s);
s = s.replaceAll("\\s","");
s = s.replaceAll("\\|",",");
System.out.println(s);
char charArray[] = s.toCharArray();
char charArrayI[] = new char[charArray.length + 1];
int j = 0;
String value = "";
for(int i = charArray.length; i > 0; i--){
charArrayI[j] = charArray[i];
value = value + charArrayI[j];
j++;
}
System.out.println("1" + value);
}catch(Exception ex){
System.out.println(ex);
}
}
}
Now in simple I just want to Separate the sizes (Which may contains the Forward Slashes) with its quantity (After last slash of each value) and store it in double array Like charArray[sizeName][Qty]. Sorry if i didn't explained my problem well as I'm Learning the Coding. but I'll provide as much info as you want.
Have you considered looking at the CAD software export to see if there is a solution on the file creation side? Or is this file coming from a third party?
OK. So, after the hard work of whole day, I've found the following solution to my problem:
import java.io.*;
import javax.swing.*;
public class ReadFileInvert2{
public static void main(String args[]){
try{
String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
System.out.println(s);
s = s.replaceAll("\\s","");
s = s.replaceAll("\\|",",");
System.out.println(s);
char charArray[] = s.toCharArray();
int x = charArray.length - 1;
charArray[x] = ',';
int no = 1;
int size = 1;
int qty = 2;
String sizeS = "";
String qtyS = "";
//String resSet[][] = new String[4][2];
String resSize[] = new String[20];
String resQty[] = new String[20];
int slashNo = 0;
String value = "";
for (int j = 1; j < charArray.length; j++){
int n = j;
if (charArray[j] == ','){
j++;
}
while (charArray[j] != ','){
if (charArray[j] == '/') {
slashNo = j;
//j++;
}
value = value + charArray[j];
//System.out.println(value);
j++;
}
for (int k = n;k < slashNo; k++ ) {
sizeS = sizeS + charArray[k];
//System.out.println(sizeS);
}
for (int l = slashNo + 1; l < j; l++ ) {
qtyS = qtyS + charArray[l];
//System.out.println(qtyS);
}
resSize[no] = sizeS;
System.out.println(resSize[no]);
resQty[no] = qtyS;
System.out.println(resQty[no]);
System.out.println("Size is: " + resSize[no] + ", and Qty is: " + resQty[no]);
no++;
slashNo = 0;
sizeS = "";
qtyS = "";
}
String fileOutput = JOptionPane.showInputDialog("Enter Output File Name: ") + ".txt";
try{
FileWriter fw = new FileWriter(fileOutput);
PrintWriter pw = new PrintWriter(fw);
String outputSize = null;
String outputQty = null;
for (int t = 1; t < no; t++) {
outputSize = resSize[t];
outputQty = resQty[t];
pw.println(outputSize + " = " + outputQty);
System.out.println("Writing: "+ outputSize + " = " + outputQty);
}
pw.flush();
pw.close();
fw.close();
fr.close();
br.close();
}catch(Exception ex){
System.out.println("Output " + ex);
}
}catch(Exception ex){
System.out.println(ex);
}
}
}
Now its in Generic form but will improve it later. But still its working fine. Thanks for your Help stack overflow Community.

How to print out a line in a textfile into 2 different lines on console Java

public static FAQ_Alisa_QnA[] oipReadQuestion(){
String questionA1,thisUser;
int indexQuestion;
String [] entryDetails;
FAQ_Alisa_QnA [] entries = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File file = new File ("ReadOIP.txt");
int count = 0;
try{
Scanner sc = new Scanner(file);
//do this while there is a next line in file.
while(sc.hasNextLine()){
String line = sc.nextLine();
entryDetails = line.split(";");
// index = entryDetails[0];
indexQuestion = Integer.parseInt(entryDetails[0]);
thisUser = entryDetails[1];
questionA1 = entryDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexQuestion = indexQuestion;
a.thisUsername = thisUser;
a.questionA1 = questionA1;
entries [count] = a;
count++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA [] allQuestions = new FAQ_Alisa_QnA [count];
for(int i = 0; i < count; i++){
allQuestions[i] = entries[i];
}
return allQuestions;
}
public static FAQ_Alisa_QnA[] oipReadAnswers(){
String indexAnswer, answer11, thisUser;
String [] answerDetails;
FAQ_Alisa_QnA [] answers = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File thisFile = new File ("AnsReadOIP.txt");
int count1 = 0;
try{
Scanner sc1 = new Scanner(thisFile);
//do this while there is a next line in file.
while(sc1.hasNextLine()){
String line = sc1.nextLine();
answerDetails = line.split(";");
// index = entryDetails[0];
indexAnswer = answerDetails[0];
thisUser = answerDetails[1];
answer11 = answerDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexAnswer = Integer.parseInt(indexAnswer);
a.thisUsername = thisUser;
a.answer11 = answer11;
answers [count1] = a;
count1++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA[] allAnswers = new FAQ_Alisa_QnA[count1];
for(int i = 0; i < count1; i++){
allAnswers[i] = answers[i];
}
return allAnswers;
}
public static void oipPrintQnA(){
FAQ_Alisa_QnA [] allQuestions = oipReadQuestion();
FAQ_Alisa_QnA [] allAnswers = oipReadAnswers();
System.out.println("Organization in project work");
System.out.println("=============================");
for(int i = 0; i < allQuestions.length; i++){
System.out.println( allQuestions[i].indexQuestion + "-" + "Question" + ":");
System.out.println(allQuestions[i].thisUsername + ":" +allQuestions[i].questionA1);
System.out.println(" ");
for(int j = 0; j < allAnswers.length; j++){
if(allQuestions[i].indexQuestion == allAnswers[j].indexAnswer){
System.out.println("Answer for question "+ + allAnswers[j].indexAnswer+ ":" );
System.out.println(allAnswers[j].thisUsername+ ":" +allAnswers[j].answer11);
System.out.println(" ");
}
}
}
}
//So I have read answers and questions and I saved my qns and answers in 2 different text files. This is because I have add functions to it but i never put it here cuz my qn is not related to that. I just wanna know how to print out the qn and answer in 2 lines so that if the qn is so long then it can print out in two lines//
So these are how my text files look like:
ReadOIP.txt
1;Shafiq;How to organize your time well when you're juggling with so many project work and assignments on the same day? Best answer:The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment.
2;Rohannah;Does having a timetable works to finish your project on time?
3;lymeoww;Is task allocation really important to be organized in project work?
AnsReadOIP.txt
1;Andy23;The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment .2; Does having a timetable to do your project works? //For example this line, it will print out very long on the console//
2;Betty23;of course it does!
1;Ying Qian;just organize lorh
3;lymeoww;Yes, it is important!
//Refer to this picture//

summing column by column in java

i have file txt in desktop :
1 5 23
2 5 25
3 30 36
i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n
Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)
{
//each sum by column
}
help me please thanks
I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,
try (Scanner sc = new Scanner(new File("patch"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
long sum = 0;
int count = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (count == 0) {
System.out.print(val);
} else {
System.out.printf(" + %d", val);
}
sum += val;
count++;
}
System.out.println(" = " + sum);
}
} catch (IOException e) {
e.printStackTrace();
}
As the Scanner(String) Constructor Javadoc documents
Constructs a new Scanner that produces values scanned from the specified string.
Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like
try (Scanner sc = new Scanner(new File("patch"))) {
List<List<Integer>> rows = new ArrayList<>();
int colCount = 0;
while (sc.hasNextLine()) {
List<Integer> al = new ArrayList<>();
String line = sc.nextLine();
Scanner row = new Scanner(line);
colCount = 0;
while (row.hasNextInt()) {
colCount++;
int val = row.nextInt();
al.add(val);
}
rows.add(al);
}
for (int i = 0; i < colCount; i++) {
long sum = 0;
for (List<Integer> row : rows) {
sum += row.get(i);
}
if (i != 0) {
System.out.print("\t");
}
System.out.print(sum);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Edit 2 For efficiencies sake, you might prefer to use a Map like
try (Scanner sc = new Scanner(new File("patch"))) {
Map<Integer, Integer> cols = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
int colCount = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (cols.containsKey(colCount)) {
val += cols.get(colCount);
}
cols.put(colCount, val);
colCount++;
}
}
for (int i : cols.values()) {
System.out.printf("%d\t", i);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Please find the code. Please go through the comments.
This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.
int sums[] = null;
while (sc.hasNextLine())
{
String row = sc.next();// get first row
String[] values = row.split(" ");// split by space
if(null == sums)
{
sums = new int[values.length];// create sum array with first row size
}
int index = 0;
for (String value : values)
{
sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
index++;
}
}
if(null != sums)
{
int index=0;
for (int sum : sums)
{
System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
index++;
}
}
If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.
Like below:
String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;
create array of arraylists of size len and store each column field in the respective arraylist.
finally, at the end apply sum on each arraylist to calculate sum of each column values.

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();
}
}

Categories