Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am writing a mergesort for an externalsort, which reads 2 chunks of data at a time from a file A, merges them into a larger chunk, and writes it to a file B. After this, I need to then read 2 of these increased chunks at a time from file B, merge them into 1 larger chunk, and write this to file A. This switching goes on until all the data counts as 1 chunk at the end.
I have tried swapping the identifiers around like this after each iteration:
RandomAccessFile temp = fileA;
fileA = fileB;
fileB = temp;
This requires, that I update the BufferedInput and BufferedOutputStreams with the new file directory names and construct them each time.
I have a limited amount of RAM, so I cannot keep creating new objects unless I have to. Is there a better way to switch the target file and source file each iteration?
A simple generic Swapable class should allow you to swap between two objects.
class Swapable<T> {
final T a;
final T b;
boolean useA = true;
Swapable(T a, T b) {
this.a = a;
this.b = b;
}
T get() {
return useA ? a : b;
}
void swap() {
useA = !useA;
}
}
Create your two RandomAccessFiles and install them in a Swapable. Use the get method to get the current file. Use the swap method to switch between them.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 days ago.
Improve this question
Say for instance I want to repeat the line of code
Integer int1 = new Integer(value1);
for many variables, such as int1 to int100. I am not asking about this exact task in particular - I am asking about any such situation where the code would be identical save for replacing small details like int1 and value1 with int2, value2. Is there a way to have the JVM complete this for me?
I am not even sure what approach to take on this or what term to search for more information. The only thing I can think to try is instead of typing "int1", having a loop that changes a string containing the name and attempting to pass the string as a symbol to the JVM but this of course does not work.
It was a little strange question and I don't know if I understood your meaning correctly or not.
But in this particular case, instead of repeating the code, you can use a data structure like an array. See Oracle tutorial.
int[] numvar = new int[arr.length];
for (int i = 0; i < args.length; i++) {
int someNumber = Integer.parseInt(args[i]);
numvar[i] = someNumber;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Why am I getting a
Null pointer access: The variable versionFromInputStream can only be null at this location
Error?
Is that because the IDE doesn't know about the read method?
byte[] versionFromInputStream = null;
if (input.read(versionFromInputStream, 0, 3) != 3)
{
throw new NetworkException();
}
double version = Double.parseDouble(versionFromInputStream.toString());
The read method of a stream expects an existing byte array with enough space to be passed. Also, the conversion of bytes to String ought to be done via the String(byte[]) constructor.
In this case, you are reading three bytes, so the following ought to suffice:
byte[] versionFromInputStream = new byte[3];
if (input.read(versionFromInputStream, 0, 3) != 3)
{
throw new NetworkException();
}
double version = Double.parseDouble(new String(versionFromInputStream));
From a design standpoint, you may want to avoid sending strings over a network as it's inefficient. As long as you have control over both the sender and the receiver, a DataInputStream/DataOutputStream will let you natively read and write integers to the stream, without the overhead of reading bytes and converting them to strings to be parsed. As a quick example showing the receive side (with an integer version):
DataInputStream dataInput = new DataInputStream(input);
int version = dataInput.readInt();
You'd need to adapt the sender to use a DataOutputStream accordingly.
So you've got a couple of things going on here that aren't right
byte[] versionFromInputStream = null; // you should initialize this like = new byte[2048]; because..
if (input.read(versionFromInputStream, 0, 3) != 3) // because here you are trying to read into this byte array. And because it hasn't been initialized, you are getting the exception
{
throw new NetworkException();
}
double version = Double.parseDouble(versionFromInputStream.toString()); // this isn't going to work either. byte[].toString is the same as Object.toString - it just prints out the location of the object in virtual memory, which isn't what you want
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to convert a C++ code to Java.
The C++ code snippet is: findMedian(array+left+i*5, 5);.
The parameter passed is the array address which changes according to the value of i. How can I modify this code so that it works in Java?The method is as below:
public int findMedian(int arr[], int n)
{
Arrays.sort(arr);
return arr[n/2]; // Return middle element
}
You can use the other overload of Arrays.sort to sort only part of the array:
public static int findMedian(int arr[], int from, int n) {
Arrays.sort(arr, from, from + n);
return arr[from + (n / 2)]; // Return middle element
}
Then call like:
findMedian(array, left + i * 5, 5);
As others have said, Java doesn't let you perform math on pointers, or really look at them at all. In general, in Java, pointers and memory are the compiler's problem, not yours.
That being said, you should still be able to look over the values in an array; just pass it a reference to the array itself, and then do whatever computations are necessary on the indices. Tough to get more specific without knowing exactly what that method does.
In java is not possible to address directly memory locations.
In C memory is addressed with a pointer.
In java memory is addressed with a reference.
For a comparison between java and C see this link from Princeton University.
Is this workable?
findMedian(array, left+i*5, 5);
Signature:
public int findMedian(int[] array, int offset, int value1) {
//...
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Problem solved : Used wrong Color Package
I am trying to read some values from an csv file, and when I put three of the numbers together, they form an rgb-value.
However, for some reason, my IDE, Netbeans, is giving me the error:
'new Color(float,float,float) has private access in the class Color'
I have no idea how using parseInt can yield a float, even after casting the result to an integer as well.
Thank you for your time and patience.
public void initBasicRGB(String definitionCSVContent) {
String[] lines = definitionCSVContent.split("\n");
String[] values;
for (String s : lines) {
values = s.split(";");
if (!s.isEmpty() && values.length==6 ) {
int red = (int)Integer.parseInt(values[1]);
int green = (int)Integer.parseInt(values[2]);
int blue = (int)Integer.parseInt(values[3]);
String nameProvince = values[4];
basicRGB.put(new Color(red,green,blue), nameProvince);
//the error is on the line above
}
}
}
I used a package from awt instead of fx
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
What function should i use for Java programming to get the total number of colons in a CSV file?
PS: not a Java developer.
Read the file char by char (using a BufferedReader to make it fast), and count each colon you meet:
int countColons() throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file.txt), "UTF-8"))) {
int count = 0;
int c;
while ((c = in.read()) >= 0) {
if (c == ':') {
count++;
}
}
return count;
}
}
Of course, you should use the appropriate encoding for your file. Not necessarily UTF-8.
Read the file line by line. For every line, use replaceAll to get rid of every character that isn't a colon. Then get the length of the resulting String. Keep a cumulative total of the results of this.
If you don't want to reinvent the wheel:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(FileUtils.readFileToString(new File("file.csv")), ":");
One cool trick I found a while ago for counting the number of occurences is to take the length of the string, and minute all the values from it that are not your desired value.
Example
// Assume fileStr contains everything in the file
int numberOfColons = fileStr.length() - fileStr.replaceAll(":", "").length();
This will give you the number of colons in the file.
Edit
Just remembered when I got it from. It is from this question.
The reason why I like this approach
Obviously, it's extremely short, which is always nice. It does give some of a hit to the processor, but it avoids all loops (in your code at least) and it seems like a very elegant solution to the problem.