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;
}
}
Related
I have implemented this java app communicating with a remote 8 modem server and when I request for an image from a security camera (error free or not) the outcome is a 1 byte image (basically a small white square). Can you help me find the error?
Here is my code:
import java.io.*;
import java.util.Scanner;
import ithakimodem.Modem;
public class g {
private static Scanner scanner = new Scanner(System.in);
private static String EchoCode = "E3369";
private static String noImageErrorscode = "M2269";
private static String imageErrorsCode = "G6637";
private static String GPS_Code = "P7302";
private static String ACK_Code = "Q2591";
private static String NACK_Code = "R4510";
public static void main(String[] args) throws IOException, InterruptedException {
int timeout = 2000;
int speed = 80000;
Modem modem = new Modem(speed);
modem.setTimeout(timeout);
modem.write("ATD2310ITHAKI\r".getBytes());
getConsole(modem);
modem.write(("test\r").getBytes());
getConsole(modem);
while (true) {
System.out.println("\nChoose one of the options below :");
System.out.print("Option 0: Exit\n" + "Option 1: Echo packages\n" + "Option 2: Image with no errors\n" + "Option 3: Image with errors\n" + "Option 4: Tracks of GPS\n"
+ "Option 5: ARQ\n" );
System.out.print("Insert option : ");
int option = scanner.nextInt();
System.out.println("");
switch (option) {
case 0: {
// Exit
System.out.println("\nExiting...Goodbye stranger");
modem.close();
scanner.close();
return;
}
case 1: {
// Echo
getEcho(modem, EchoCode);
break;
}
case 2: {
// Image with no errors
getImage(modem, noImageErrorscode, "no_error_image.jpg");
break;
}
case 3: {
// Image with errors
getImage(modem, imageErrorsCode, "image_with_errors.jpg");
}
case 4: {
// GPS
getGPS(modem, GPS_Code);
break;
}
case 5: {
// ARQ
getARQ(modem, ACK_Code, NACK_Code);
break;
}
default:
System.out.println("Try again please\n");
}
}
}
public static String getConsole(Modem modem) {
int l;
StringBuilder stringBuilder= new StringBuilder();
String string = null;
while (true) {
try {
l = modem.read();
if (l == -1) {
break;
}
System.out.print((char) l);
stringBuilder.append((char) l);
string = stringBuilder.toString();
} catch (Exception exc) {
break;
}
}
System.out.println("");
return string;
}
private static void getImage(Modem modem, String password, String fileName) throws IOException {
int l;
boolean flag;
FileOutputStream writer = new FileOutputStream(fileName, false);
flag = modem.write((password + "\r").getBytes());
System.out.println("\nReceiving " + fileName + "...");
if (!flag) {
System.out.println("Code error or end of connection");
writer.close();
return;
}
while (true) {
try {
l = modem.read();
writer.write((char) l);
writer.flush();
if (l == -1) {
System.out.println("END");
break;
}
}
catch (Exception exc) {
break;
}
}
writer.close();
}
private static void getGPS(Modem modem, String password) throws IOException {
int rows = 99;
String Rcode = "";
Rcode = password + "R=10200" + rows;
System.out.println("Executing R parameter = " + Rcode + " (XPPPPLL)");
modem.write((Rcode + "\r").getBytes());
String stringConsole = getConsole(modem);
if (stringConsole == null) {
System.out.println("Code error or end of connection");
return;
}
String[] stringRows = stringConsole.split("\r\n");
if (stringRows[0].equals("n.a")) {
System.out.println("Error : Packages not received");
return;
}
System.out.println("**TRACES**\n");
float l1 = 0, l2 = 0;
int difference = 8;
difference *= 100 / 60;
int traceNumber = 7;
String[] traces = new String[traceNumber + 1];
int tracesCounter = 0, flag = 0;
for (int i = 0; i < rows; i++) {
if (stringRows[i].startsWith("$GPGGA")) {
if (flag == 0) {
String str = stringRows[i].split(",")[1];
l1 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
flag = 1;
}
String str = stringRows[i].split(",")[1];
l2 = Integer.valueOf(str.substring(0, 6)) * 100 / 60;
if (Math.abs(l2 - l1) >= difference) {
traces[tracesCounter] = stringRows[i];
if (tracesCounter == traceNumber)
break;
tracesCounter++;
l1 = l2;
}
}
}
for (int i = 0; i < traceNumber; i++) {
System.out.println(traces[i]);
}
String w = "", T_cd_fnl = password + "T=";
int p = 1;
System.out.println();
for (int i = 0; i < traceNumber; i++) {
String[] strSplit = traces[i].split(",");
System.out.print("T parameter = ");
String str1 = strSplit[4].substring(1, 3);
String str2 = strSplit[4].substring(3, 5);
String str3= String.valueOf(Integer.parseInt(strSplit[4].substring(6, 10)) * 60 / 100).substring(0, 2);
String str4= strSplit[2].substring(0, 2);
String str5= strSplit[2].substring(2, 4);
String str6= String.valueOf(Integer.parseInt(strSplit[2].substring(5, 9)) * 60 / 100).substring(0, 2);
w = str1 + str2 + str3 + str4 + str5 + str6 + "T";
p = p + 5;
System.out.println(w);
T_cd_fnl = T_cd_fnl + w + "=";
}
T_cd_fnl = T_cd_fnl.substring(0, T_cd_fnl.length() - 2);
System.out.println("\nSending code: " + T_cd_fnl);
getImage(modem, T_cd_fnl, "traces GPS.jpg");
}
private static void getEcho(Modem modem, String strl) throws InterruptedException, IOException {
FileOutputStream echo_time_writer = new FileOutputStream("echoTimes.txt", false);
FileOutputStream echo_counter_writer = new FileOutputStream("echoCounter.txt", false);
int h;
int runtime = 5, packetCounter = 0;
String str = "";
System.out.println("\nRuntime (mins) = " + runtime + "\n");
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receiveTime = 0;
String time = "", ClockTime = "";
echo_time_writer.write("Clock Time\tSystem Time\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
packetCounter++;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
while (true) {
try {
h = modem.read();
System.out.print((char) h);
str += (char) h;
if ( h== -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (str.endsWith("PSTOP")) {
receiveTime = System.currentTimeMillis();
ClockTime = str.substring(18, 26) + "\t";
time = String.valueOf((receiveTime - send_time) + "\r\n");
echo_time_writer.write(ClockTime.getBytes());
echo_time_writer.write(time.getBytes());
echo_time_writer.flush();
str = "";
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
}
echo_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
echo_counter_writer.write(("\r\nPackets Received: " + String.valueOf(packetCounter)).getBytes());
echo_counter_writer.close();
echo_time_writer.close();
}
private static void getARQ(Modem modem, String strl, String nack_code) throws IOException, InterruptedException {
FileOutputStream arq_time_writer = new FileOutputStream("ARQtimes.txt", false);
FileOutputStream arq_counter_writer = new FileOutputStream("ARQcounter.txt", false);
int runtime = 5;
int xor = 1;
int f = 1;
int m;
int packageNumber = 0;
int iterationNumber = 0;
int[] nack_times_counter = new int[15];
int nack_to_package = 0;
String time = "", clock_time = "", s = "";
long start_time = System.currentTimeMillis();
long stop_time = start_time + 60 * 1000 * runtime;
long send_time = 0, receive_time = 0;
System.out.printf("Runtime (mins) = " + runtime + "\n");
arq_time_writer.write("Clock Time\tSystem Time\tPacket Resends\r\n".getBytes());
while (System.currentTimeMillis() <= stop_time) {
if (xor == f) {
packageNumber++;
nack_times_counter[nack_to_package]++;
nack_to_package = 0;
send_time = System.currentTimeMillis();
modem.write((strl + "\r").getBytes());
} else {
iterationNumber++;
nack_to_package++;
modem.write((nack_code + "\r").getBytes());
}
while (true) {
try {
m = modem.read();
System.out.print((char) m);
s += (char) m;
if (m == -1) {
System.out.println("\nCode error or end of connection");
return;
}
if (s.endsWith("PSTOP")) {
receive_time = System.currentTimeMillis();
break;
}
} catch (Exception e) {
break;
}
}
System.out.println("");
String[] string = s.split("<");
string = string[1].split(">");
f = Integer.parseInt(string[1].substring(1, 4));
xor = string[0].charAt(0) ^ string[0].charAt(1);
for (int i = 2; i < 16; i++) {
xor = xor ^ string[0].charAt(i);
}
if (xor == f) {
System.out.println("Packet ok");
receive_time = System.currentTimeMillis();
time = String.valueOf((receive_time - send_time) + "\t");
clock_time = s.substring(18, 26) + "\t";
arq_time_writer.write(clock_time.getBytes());
arq_time_writer.write(time.getBytes());
arq_time_writer.write((String.valueOf(nack_to_package) + "\r\n").getBytes());
arq_time_writer.flush();
} else {
xor = 0;
}
s = "";
}
arq_counter_writer.write(("\r\nRuntime: " + String.valueOf(runtime)).getBytes());
arq_counter_writer.write("\r\nPackets Received (ACK): ".getBytes());
arq_counter_writer.write(String.valueOf(packageNumber).getBytes());
arq_counter_writer.write("\r\nPackets Resent (NACK): ".getBytes());
arq_counter_writer.write(String.valueOf(iterationNumber).getBytes());
arq_counter_writer.write("\r\nNACK Time Details".getBytes());
for (int i = 0; i < nack_times_counter.length; i++) {
arq_counter_writer.write(("\r\n" + i + ":\t" + nack_times_counter[i]).getBytes());
}
arq_counter_writer.close();
arq_counter_writer.close();
System.out.println("Packets Received: " + packageNumber);
System.out.println("Packets Resent: " + iterationNumber);
System.out.println("\n\nFile arqTimes.txt is created.");
System.out.println("File arqCounter.txt is created.");
}
}
I know the problem is most probably in the getImage() function but I haven't figured it out yet.
I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}
I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.
Okay following is my Simmulation.java file and I am supposed to write main method for it to work. But I have no idea how to do it.
I have tried like following, but it didn't work!
public static void main(String args[])
{
new Simmulation(args[0]);
}
Any help is much appreciated. Thank you in advance
This is my Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation
{
Queue < CashewPallet > inputQueue = new LinkedList < CashewPallet > ();
Stack < CashewPallet > stBay1 = new Stack < CashewPallet > ();
Stack < CashewPallet > stBay2 = new Stack < CashewPallet > ();
FileOutputStream fout4;
PrintWriter pw;
static int tick = 0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index = 0;
String nutType = "";
int id = 0;
Scanner s2;
try
{
sc = new Scanner(new File(fn));
fout4 = new FileOutputStream("nuts.txt");
pw = new PrintWriter(fout4, true);
String eol = System.getProperty("line.separator"); // Reading string line by line
while (sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if (s2.hasNext())
{
while (s2.hasNext())
{
String s = s2.next();
if (index == 0)
{
nutType = s;
}
else
{
id = Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype " + nutType + " Id is " + id + "tick " + tick);
if ((nutType.equalsIgnoreCase("A") || nutType.equalsIgnoreCase("P") || nutType.equalsIgnoreCase("C") || nutType.equalsIgnoreCase("W")) && id != 0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(), id));
System.out.println("Size of Queue " + inputQueue.size());
int k = 0;
if (!inputQueue.isEmpty())
{
while (inputQueue.size() > k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index = 0;
if (!stBay2.isEmpty())
{
while (!stBay2.isEmpty())
{
c1 = stBay2.pop();
temp = tick + " " + c1.getNutType() + " " + c1.getId() + eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp = tick + eol;
fout4.write(temp.getBytes());
}
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
}
closeStream();
}
public CashewPallet process(CashewPallet c)
{
// CashewPallet c=new CashewPallet();
int k = 0;
// while(stBay.size()>k)
// {
// c=stBay.pop();
String operation = c.getNutType();
if (c.getPriority() == 1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch (operation)
{
case "A":
shelling(c);
washing(c);
packing(c);
break;
case "C":
washing(c);
packing(c);
break;
case "W":
washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch (Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for " + c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for " + c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for " + c.getNutType());
}
stBay2.push(c);
return true;
}
The problem is that you are not passing any parameters to the program. So the length of the args is 0. What you can try is to check for the length of the args passed before using it.
if (args.length > 0)
new Simulation(args[0]);
else
new Simulation("Default value");
That should solve your problem.
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();
}
}