This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
In File1.java I have-
public static int[] dataArray = new int[100];
in File2.java I am accessing it as -
private static int[] data = new int[File1.dataArray.length];
for(int i=0; i<File1.dataArray.length; i++) {
if(File1.array1[i] == 0)
continue;
data[i] = File1.array1[i];}
Is this the right way or can I do like this-
private static int[] data = File1.dataArray;
to copy it? Any help appreciated. Thanks!
Yes, you can do
private static int[] data = File1.dataArray;
But there is a HUGE DANGER doing it that way and therefore I wouldn't call it the right way to COPY arrays, because you are not REALLY copying.
See this code. It demonstrates what happens.
public class File1
{
public static int[] dataArray = new int[100];
static
{
for (int i=0; i<100; i++)
{
dataArray[i] = i;
}
}
}
public class File2
{
private static int[] data = File1.dataArray; // makes "data" refer to the SAME array as File1.dataArray
public static void main(String[] args)
{
File2 file2 = new File2();
file2.data[20] = -567; // this changes File1.dataArray also!
System.out.println(File1.dataArray[20]); // prints -567
}
}
Therefore, use System.arrayCopy() to copy arrays, as Jarrod suggested. Of course, you can also copy by writing your own code like this -
private static int[] data = new int[File1.dataArray.length];
static
{
for(int i = 0; i < File1.dataArray.length; i++)
{
data[i] = File1.dataArray[i];
}
}
Look up System.arraycopy() to copy arrays.
It isn't clear what the presented code has to do with Files as referenced in your title?
Also your presented code is incomplete, won't compile and isn't clear or idiomatic Java.
This will most likely get closed if you don't make it clearer what you want to do.
Related
I'm porting some image processing code from C++ to Java. My C++ code has template classes that define mixed-mode image arithmetic. I'm trying to do the same in Java but it's clear that I don't understand the concepts needed to do it. Currently, I'm trying to write a generic method.
private void DoMyRoutine()
{
float[] data = {1.1f,2.2f,3.3f};
Float[] fArr = new Float[data.length]; // Is there a better way to do this?
for(int i = 0; i< data.length;i++)
{
fArr[i] = data[i];
}
fArr = Test(fArr);
}
//*********************************************************************************************
private <T> T[] Test( T[] myData)
{
Float inc = new Float(2.0f);
for(int i=0;i<myData.length;i++)
{
// I can see the myData array values in the debugger
// This clearly doesn't work, is there a method"
myData[i] = inc;
}
return myData;
}
Am I even on the right track? I'm relatively new to Java and still struggling with some of the concepts and syntax.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This is my code. I just read file that have lines first is number then lines as string their number equal the number in first line.
import java.io.*;
import java.util.*;
class groupmember
{
int recieving;
int giving;
String name;
groupmember()
{
recieving=0;
giving=0;
//name=null;
}
public void setname (String Title)
{
this.name = new String(Title);
}
public void setrecieving(int val)
{
recieving=val;
}
public void setgiving(int val)
{
giving=val;
}
public String getname()
{
return name;
}
public int getrecieving()
{
return recieving;
}
public int getgiving()
{
return giving;
}
}
class gift1 {
/**
* #param args
*/
public static void main(String[] args) throws IOException{
BufferedReader f=new BufferedReader(new FileReader("gift1.in"));
PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
StringTokenizer st=new StringTokenizer(f.readLine());
int NP=Integer.parseInt(st.nextToken());
int excpectedgived=0,div=0;
groupmember []groupmember=new groupmember[NP];
for(int i=0;i<NP;i++)
{
st=new StringTokenizer(f.readLine());
String name=st.nextToken();
groupmember[i].setname(name);
System.out.println(name);
}
out.close();
}
}
The problem arises on this line:
groupmember[i].setname(name);
It causes NullPointerException. I want to know why this happens.
An array of reference type variables is filled with null entries after initialization. You need
groupmember[i] = new groupmember();
before you can do:
groupmember[i].setname(name);
In future, please follow the Java Naming Conventions and have your classes start with an uppercase letter, like GroupMember (even CamelCase).
groupmember[i] is never defined, you need to add
groupmember[i] = new groupmember();
or something like that at the start of your cycle.
You have just initialised the array of type groupmember, now all the values in the array are null, in order to start using the array, you need to do .
groupmember[i] = new groupmember();
Do this: String name = ""; String have default value null if they are not initialized.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}
Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In my project I have a server that handles multiple clients that connect to it. Each time a client is connected, a new "Guitar" is created, specific to that client on a new thread. Each "Guitar" is an array of 12 guitar strings, and when a key corresponding to a string is pressed in the client window, that guitar's string is plucked.
I have a method called notePlayed(char key) in my Guitar class that "plucks" the string and adds all of the "plucks" into the combined audio to be played. However, I am running into this error anytime it is called:
key pressedj
Exception in thread "Thread-4" java.lang.NullPointerException
notePlayed accessed
at Guitar.notePlayed(Guitar.java:29)
at GuitarListener.run(GuitarServer.java:33)
at java.lang.Thread.run(Thread.java:680)
My guitarserver looks like this:
class GuitarListener implements Runnable {
private Socket sock;
private GuitarListenerGui gui;
private Guitar guitar;
public GuitarListener(Socket s, GuitarListenerGui g, Guitar gt) {
this.sock = s;
this.gui = g;
this.guitar = gt;
}
public void run() {
boolean loop=true;
try {
//setting up printwriters and bufferedreaders removed
System.out.println("key pressed" + key);
Guitar.notePlayed(key);
}
with the new Guitar and threads created in the GuitarServer class further down
String keyboard ="qwertyuiop[]";
GuitarString[] gStrings = new GuitarString[keyboard.length()];
Guitar guitar = new Guitar(gStrings, keyboard);
GuitarListener job = new GuitarListener(serverSocket.accept(), gui, guitar);
// start a new thread to handle the connection
Thread t = new Thread(job);
t.start();
and my Guitar class looks like this:
public class Guitar {
private static String keyboard;;
private static GuitarString[] gStrings;
public Guitar (GuitarString[] gStrings, String keyboard){
this.keyboard=keyboard;
this.gStrings=gStrings;
}
with the for-loop causing the error here:
public static void notePlayed (char key){
double sample=0.0;
for (int i=0; i<keyboard.length(); i++){//adds all of the strings to sample to be played
sample+=gStrings[i].sample();
Sorry about the length of the post, but can anybody point me in the right direction or let me know how far off I am? Thanks in advance. I am happy to answer anymore questions you may have.
In the main function of Guitar I initialize the guitarstrings with this loop:
for(int i=0;i<keyboard.length();i++){
double iNote = 440.0* Math.pow(2, i/12.0);//puts the correct frequency with each string
System.out.println(iNote);
gStrings[i] = new GuitarString(iNote);
}
GuitarString[] gStrings = new GuitarString[keyboard.length()];
will result in an array of GuitarString objects with the size of keyboard.length() all initialized with null value. You have to initialize each GuitarString object in the array before using it in the for loop in the line sample+=gStrings[i].sample();
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am having trouble with sorting my linked list can anyone help me and let me know what I am doing wrong?
I need to sort in and put it in a list.
and If you can give me some pointers to print the list at the end with a new method public void print().
public class SortedLinkedList<T extends Comparable<? super T>>
extends LinkedList<T>
{
private LinkedList<T> list; //the sorted list
//the constructor
public SortedLinkedList(LinkedList<T> in)
{
if(in.isEmpty())
{
System.out.println("Empty list");
}
else
{
LinkedList<T> first = new LinkedList<T>(in.subList(0, in.size()/2));
LinkedList<T> second = new LinkedList<T>(in.subList(in.size ()/2,in.size()));
LinkedList<T> sortList = new LinkedList<T>();
int i = 0;
int j = 0;
while(i<first.size() && j<second.size())
{
if(first.get(i).equals(second.get(j)) || first.get(i).compareTo(second.get(j))<0)
{
sortList.add(first.get(i));
i++;
}
else
{
sortList.add(second.get(j));
j++;
}
if(i == first.size())
{
for(int k = j; k<second.size(); k++)
{
sortList.add(second.get(k));
}
}
else
{
for(int x = i; x<first.size(); x++)
{
sortList.add(first.get(x));
}
}
}
}
}
}
Before writing your own sort try Collections.sort. If you need your own sort order, use a Comparator.
Some addition: In most cases, LinkedLists are the wrong data structure - especially if there's the need for sorting it.
It seems you are trying to implement Mergesort. If my assumption is correct, you are forgetting to call mergesort on the sublists.recursively. The rough algorithm, in pseudo code, would be:
mergesort(list)
left = list[:len(list/2)]
right = list[len(list/2):]
mergesort(left)
mergesort(right)
merge(left, right) # that would be your while loop
Edit: Unless you really need to implement your own algorithm, I suggest using Collections.sort, from the Java API.