issues with 1D java array - java

I'm getting a null pointer exception in one of my java classes.
I have been looking at this thing for ever now and I could use another set of eyes.
I have 2 Class files:
FileParser:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package photouploader;
import java.nio.*;
import java.io.*;
import java.util.*;
/**
*
* #author 10339
*/
public class fileParser {
/*var Decleration*/
private File dir;
private File [] Files;
public String [] Filernames;
/*Accessor Methods*/
public File getDir(){
return dir;
}
public void SetDir(File directory){
dir=directory;
}
public File[] getFiles(){
return Files;
}
public void setFiles(File [] matches){
Files=matches.clone();
}
public String [] getFilenames(){
return Filernames;
}
public void setFilenames(){
for(int i=0;i<Files.length;i++){
System.out.println(Files[i].toString());
System.out.println(Files[i].toString().substring(Files[i].toString().lastIndexOf("\\")+1));
Filernames[i]=Files[i].toString().substring(Files[i].toString().lastIndexOf("\\")+1);
}
}
}
Photo Uploader Class file/Main:
package photouploader;
import javax.swing.*;
import java.io.*;
/**
*
* #author 10339
*/
public class PhotoUploader {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = j.showOpenDialog(null);
if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION){
File dir = j.getSelectedFile();
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir,String name)
{
return name.endsWith(".png")||name.endsWith(".jpg");
}
});
if(matches.length==0){
JOptionPane.showMessageDialog(null,"you have not chosen "
+ "a valid directory");
}
else{
fileParser FP = new fileParser();
FP.setFiles(matches);
FP.setFilenames();
/* Form FJP = new Form();
FJP.setVisible(true);*/
NewJFrame JP = new NewJFrame();
JP.setVisible(true);
JP.update_Upload_list(FP.getFilenames());
}
}
else{
JOptionPane.showMessageDialog(null,"you have not chosen "
+ "a valid directory");
}
}
}
I have attempted to just place data # position 0 of Filternames and it is still freaking out.
Have I missed something?
do I need to Declare the size of the Array before use?
Thanks,
Scorliss

You have to allocate memory for the array elements:
Filernames = new String[Files.length];
EDIT:
So declaration is not enough?
No. In a nutshell, when you declare the variable, you are just saying that "this variable will point to an array". In that moment, it doesn't hold any array at all. You have to asign an array to the variable in order to use it. You can read a bit more about array basics here.

The String[] Filernames, has not been declared like: String[] Filernames = new String[5];
(or = new String[some length];) Also you should follow Java code conventions such as only class names begin with a capital letter, and variable names start with lower case letters.

Related

School Java Escape Room Program

I am writing an escape room project for school which has messages such as a greeting, a win message, a loss message, etc. I stored these messages in a text file and then I read the file and store each line into one ArrayList and to access each line by their respective getter method and I use the .get function with their index value. I'm wondering if there is a way to avoid hardcoding the index numbers and on top of that is there a way I can just read the file when the program is run instead of having to make an instance of the class and then for example doing foo.readFile();
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.ArrayList;
//package Stage;
public class EscapeRoom{
ArrayList<String> Messages;
String fileName;
private boolean win = false;
public void readFile() throws FileNotFoundException {
Messages = new ArrayList<String>();
fileName = "test.txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
Messages.add(scanner.nextLine());
}
scanner.close();
}
public void showGreeting(){
System.out.println(Messages.get(0));
}
public void showDirections(){
System.out.println(Messages.get(1));
}
public void showWin() {
System.out.println(Messages.get(2));
}
public void showLoss() {
System.out.println(Messages.get(3));
}
}
This is exactly what a properties file is for. Here is a file I named prompts.properties:
greeting = "hello, welcome to my game"
win = "you win, yay"
loss = "sorry bro, you lose"
directions = "escape with your life!"
Here is your modified program:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class EscapeRoom {
Properties prompts = null;
public void readFile() throws IOException {
prompts = new Properties();
prompts.load(new FileInputStream("prompts.properties"));
}
public void showGreeting() {
System.out.println(prompts.get("greeting"));
}
public void showDirections() {
System.out.println(prompts.get("directions"));
}
public void showWin() {
System.out.println(prompts.get("win"));
}
public void showLoss() {
System.out.println(prompts.get("loss"));
}
}
Basically to get a named key-value pair you want something like a map. Properties are really a special sort of map that understands a file of records that have the format <key> = <value>.
Here is the documentation on Properties and if you decide to roll your own you would implement the same basic thing with a Map.

Taking a CSV file, splitting it, and adding each split part into an attribute of an object

I am at a sticking point with an assignment I have been working on. It is a program that creates a Periodic Table of the Elements. To create each element, I need to take a file(a CSV), split it, and set each split part as an attribute of an object called "Element". Splitting each line of the file and reading it in has so far been no problem. However, I have been stuck on how to take each part and add it as the attribute of the Element object. Can anyone please shed some light on this?
Here is my code:
"Periodic Table" class:
public class PeriodicTable {
private String line;
private String[] parts;
private String filename = "file.csv";
public PeriodicTable() throws IOException {
}
public void readValues(String filename) throws IOException{
Scanner sc = new Scanner(new FileReader(filename));
ArrayList<Element> ar1 = new ArrayList<Element>();
while(sc.hasNextLine()){
line = sc.nextLine();
parts = line.split(",");
Element el = new Element();
el.setChemicalName(parts[0]);
el.setAtomNum(parts[1]);
el.setMeltPoint(parts[3]);
el.setBoilPoint(parts[4]);
el.setDensity(parts[5]);
el.setAtomWeight(parts[6]);
// System.out.println(el.getChemicalName());
//System.out.println(el.getAtomWeight());
ar1.add(el);
}
System.out.println(ar1);
}
}
The "Element" class
public class Element {
private String chemicalName;
private String atomNum;
private String boilPoint;
private String meltPoint;
private String density;
private String atomWeight;
public Element() throws IOException{
}
/**
* #return the chemicalName
*/
public String getChemicalName() {
return chemicalName;
}
/**
* #param chemicalName the chemicalName to set
*/
public void setChemicalName(String chemicalName) {
this.chemicalName = chemicalName;
}
/**
* #return the atomNum
*/
public String getAtomNum() {
return atomNum;
}
/**
* #param atomNum the atomNum to set
*/
public void setAtomNum(String atomNum) {
this.atomNum = atomNum;
}
/**
* #return the boilPoint
*/
public String getBoilPoint() {
return boilPoint;
}
/**
* #param parts2 the boilPoint to set
*/
public void setBoilPoint(String parts2) {
this.boilPoint = parts2;
}
/**
* #return the meltPoint
*/
public String getMeltPoint() {
return meltPoint;
}
/**
* #param parts2 the meltPoint to set
*/
public void setMeltPoint(String parts2) {
this.meltPoint = parts2;
}
/**
* #return the density
*/
public String getDensity() {
return density;
}
/**
* #param density the density to set
*/
public void setDensity(String density) {
this.density = density;
}
/**
* #return the atomWeight
*/
public String getAtomWeight() {
return atomWeight;
}
/**
* #param input the atomWeight to set
*/
public void setAtomWeight(String input) {
this.atomWeight = input;
}
#Override
public String toString(){
return chemicalName;
}
}
Because the String.split() method uses an array to hold each part that is split, I tried to set the values to each attribute using a reference to the index in the parts array that holds the value, for example....
el.setChemicalName(parts[0]));
However, this doesn't seem to be working - when I try to print out the value of that variable, I usually get a null value.
I recommend you to use OpenCSV to make your life easier.
Your code work fine, but please
Check the variable filename , maybe you pass an wrong value when call the method readValues.
Are you sure the token separator of your CSV file is a comma ",". If you're using an office application (Excel in MS Office or Calc in Libre/Open Office) if you don't especify the token the default separator is a semicolon ";".
In method String.split it's better use parts = line.split("\\,"); because split use and regular expressions to make the separation in String array.

Passing variable values to the eval function

When this piece of code is executed the program uses the matlabcontrol library to open MATLAB and execute the given lines inside the eval(). The problem is in the first line i.e. m.eval("image1=imread('D:/My Hand Gestures/f.jpg');"); takes a fixed String value as input. But here i want to store the path in a variable and pass it to the imread() function. How am i supposed to do that? Any help is appreciated. Here is the code.
package Interface;
import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;
/**
*
* #author Rajdeep
*/
public class Output {
private static String check;
private static String path;
Output(){
//default constructor
}
Output(String s,String p){
check = s;
path=p;
}
//GrayScale Conversion Function
public static void grayScale(String p,MatlabProxy m)throws MatlabConnectionException, MatlabInvocationException{
m.eval("image1=imread('D:/My Hand Gestures/f.jpg');");
m.feval("image1","imread(path)");
m.eval("figure,imshow(image1);");
m.eval("image_gray=rgb2gray(image1);");
m.eval("figure,imshow(image_gray);");
m.eval("final_image=imresize(image_gray,0.03125);");
m.eval("figure,imshow(final_image);");
m.eval("imwrite(final_image,'C:/Users/Desktop/f.jpg');");
//Disconnect the proxy from MATLAB
m.disconnect();
}
//Median Filtering Function
public static void Filter(String p, MatlabProxy m)throws MatlabConnectionException, MatlabInvocationException{
m.eval("I=imread('D:/gestures/f.jpg');");
m.eval("J = medfilt2(I, [4 4]);");
m.eval("figure,imshow(J);");
m.eval("imwrite(J,'C:/Users/Rajdeep/Desktop/f.jpg');");
//Disconnect the proxy from MATLAB
m.disconnect();
}
/**
*
* #param args
* #throws MatlabConnectionException
* #throws MatlabInvocationException
*/
public static void main(String[] args) throws MatlabConnectionException, MatlabInvocationException
{
//Create a proxy, which we will use to control MATLAB
MatlabProxyFactory factory = new MatlabProxyFactory();
MatlabProxy proxy = factory.getProxy();
Output out=new Output("GrayScale","D:/My Hand Gestures/f.jpg");
if(check == "GrayScale") {
grayScale(path, proxy);
}
if(check== "Filter"){
Filter(path,proxy);
}
}
}
Here i created a path variable that has a predefined path. I want to use this variable instead of giving the path as in the above mentioned process.
I would try this to start with. See if it helps.
String path_variable = "D:/My Hand Gestures/f.jpg";
m.eval("image1=imread('" + path_variable + "');");

Accessing values from another thread

My question is: How do I access values from another thread?
I have two .java files, Main.java and TrackHands.java
Main.java
/**
* This is the main class, it is used to start the program. The only use of this
* is to make everything more organized.
*/
package Kinect;
//import processing.core.PApplet;
/**
* #author Tony Nguyen <Tony.Nguyen#HvA.nl>
*
*/
public class Main
{
public static void main(String _args[])
{
Thread trackHands = new Thread(new TrackHands());
trackHands.start();
}
}
TrackHands.java
/*
* This uses the normal Java layout to track the user and prints out the coordinates of the left and right hand
*/
package Kinect;
import SimpleOpenNI.*;
import processing.core.PApplet;
import processing.core.PVector;
/**
* #author Tony Nguyen <Tony.Nguyen#HvA.nl>
* #version 1.0
*/
public class TrackHands extends PApplet implements Runnable
{
private int handLeftX, handLeftY = 0; // Holds the coordinates of the left hand
SimpleOpenNI kinect = new SimpleOpenNI(this); // kinect object
/**
* Constructor Takes no parameters
*/
public TrackHands()
{
}
/**
* run This will be executed when the thread starts
*/
#Override
public void run()
{
IntVector userList = new IntVector(); // Make a vector of ints to store the list of users
PVector leftHand = new PVector(); // Make a vector to store the left hand
PVector convertedLeftHand = new PVector();
kinect.enableDepth();
kinect.enableUser(SimpleOpenNI.SKEL_PROFILE_ALL);
kinect.setMirror(true);
while (true)
{
kinect.update();
kinect.getUsers(userList); // Write the list of detected users into the vector
if (userList.size() > 0) // Checks if a user is found
{
int userId = userList.get(0); // Get first user
if (kinect.isTrackingSkeleton(userId)) // If successfully calibrated
{
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_LEFT_HAND, leftHand); // Put the position of the left hand into that vector
kinect.convertRealWorldToProjective(leftHand,
convertedLeftHand);
this.handLeftX = round(convertedLeftHand.x);
this.handLeftY = round(convertedLeftHand.y);
}
}
}
}
// User-tracking callbacks!
public void onNewUser(int userId)
{
System.out.println("Start pose detection");
kinect.startPoseDetection("Psi", userId);
}
public void onEndCalibration(int userId, boolean successful)
{
if (successful)
{
System.out.println(" User calibrated !!!");
kinect.startTrackingSkeleton(userId);
} else
{
System.out.println(" Failed to calibrate user !!!");
kinect.startPoseDetection("Psi", userId);
}
}
public void onStartPose(String pose, int userId)
{
System.out.println("Started pose for user");
kinect.stopPoseDetection(userId);
kinect.requestCalibrationSkeleton(userId, true);
}
}
I have tried to use a getter and a setter to get the values from TrackHands.java into another thread.
Tried creating objects and passing the values as parameters, but then my program will not use these new values in the run() method.
To get values from TrackHands, use a get method that accesses an instance variable that is set in run()
class TrackHands {
Object output;
public void run() {
while(true) {
output = new Object();
}
}
public Object getOutput() {
return output;
}
}
Pass TrackHands into your consumer object and use it to call get getOutput() method.
Passing values in is a bit trickier, because you might cause race condition. Try something like this
class TrackHands {
Object input = null;
public boolean setInput(Object input) {
if(this.input == null) {
this.input = input;
return true;
} else {
return false;
}
}
}
When your run() method uses input, set it to null so that another thread can pass in another input. Your producer thread will use this loop to pass in input:
public void sendInput(TrackHands th, Object input) {
boolean done = false;
while(!done) {
done = th.setInput(input);
}
}
This will keep trying to pass in input until it succeeds.
setInput uses the synchronized keyword so that only one thread can call this method at once, otherwise you'll get a race condition.
A friend of mine solved my problem.
I want to thank everyone for helping me!
Main.java
/**
* This is the main class, it is used to start the program. The only use of this
* is to make everything more organized.
*/
package Kinect;
//import processing.core.PApplet;
/**
* #author Tony Nguyen <Tony.Nguyen#HvA.nl>
*
*/
public class Main
{
public static void main(String _args[])
{
// PApplet.main(new String[]
// {
// Sensor.class.getName()
// });
ValueStore valueStore = new ValueStore(); // ADDED THIS LINE
Thread trackHands = new Thread(new TrackHands(valueStore)); // ADDED THIS LINE
trackHands.start();
}
}
TrackHands.java
/*
* This uses the normal Java layout to track the user and prints out the coordinates of the left and right hand
*/
package Kinect;
import SimpleOpenNI.*;
import processing.core.PApplet;
import processing.core.PVector;
/**
* #author Tony Nguyen <Tony.Nguyen#HvA.nl>
* #version 1.0
*/
public class TrackHands extends PApplet implements Runnable
{
private int handLeftX, handLeftY, handRightX, handRightY = 0; // Holds the coordinates of the left hand
SimpleOpenNI kinect = new SimpleOpenNI(this); // kinect object
private ValueStore valuesStore; // ADDED THIS LINE
/**
* Constructor Takes no parameters
*/
public TrackHands()
{
}
public TrackHands(ValueStore valuesStore)
{
this.valuesStore = valuesStore;
}
/**
* run This will be executed when the thread starts
*/
#Override
public void run()
{
IntVector userList = new IntVector(); // Make a vector of ints to store the list of users
PVector leftHand = new PVector(); // Make a vector to store the left hand
PVector rightHand = new PVector(); // Make a vector to store the right hand
PVector convertedLeftHand = new PVector(); // Make a vector to store the actual left hand
PVector convertedRightHand = new PVector(); // Make a vector to store the actual right hand
kinect.enableDepth();
kinect.enableUser(SimpleOpenNI.SKEL_PROFILE_ALL);
kinect.setMirror(true);
while (true)
{
kinect.update();
kinect.getUsers(userList); // Write the list of detected users into the vector
if (userList.size() > 0) // Checks if a user is found
{
int userId = userList.get(0); // Get first user
if (kinect.isTrackingSkeleton(userId)) // If successfully calibrated
{
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_LEFT_HAND, leftHand); // Put the position of the left hand into that vector
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_RIGHT_HAND, rightHand); // Put the position of the left hand into that vector
kinect.convertRealWorldToProjective(leftHand,
convertedLeftHand);
kinect.convertRealWorldToProjective(rightHand,
convertedRightHand);
this.handLeftX = round(convertedLeftHand.x);
this.handLeftY = round(convertedLeftHand.y);
this.handRightX = round(convertedRightHand.x);
this.handRightY = round(convertedRightHand.y);
valuesStore.setHandValues(handLeftX, handLeftY, handRightX, handRightY); // ADDED THIS LINE
}
}
}
}
// User-tracking callbacks!
public void onNewUser(int userId)
{
System.out.println("Start pose detection");
kinect.startPoseDetection("Psi", userId);
}
public void onEndCalibration(int userId, boolean successful)
{
if (successful)
{
System.out.println(" User calibrated !!!");
kinect.startTrackingSkeleton(userId);
} else
{
System.out.println(" Failed to calibrate user !!!");
kinect.startPoseDetection("Psi", userId);
}
}
public void onStartPose(String pose, int userId)
{
System.out.println("Started pose for user");
kinect.stopPoseDetection(userId);
kinect.requestCalibrationSkeleton(userId, true);
}
}
Then added a class to store the values so another class can access it.
ValueStore.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Kinect;
/**
*
* #author Tony Nguyen <Tony.Nguyen#HvA.nl>
*/
public class ValueStore
{
private int leftX, leftY, rightX, rightY = 0;
public void setHandValues(int leftX, int leftY, int rightX, int rightY)
{
this.leftX = leftX;
this.leftY = leftY;
this.rightX = rightX;
this.rightY = rightY;
}
public int getLeftX()
{
return this.leftX;
}
}

Determine file being used by FileHandler

I am creating a java.util.logging.FileHandler that is allowed to cycle through files. When multiple instances of my application are run, a new log file is created for each instance of the application. I need to know what file is being used by the application because I want to upload the log file to my servers for further review. How can I tell what file is being used by a certain FileHandler?
The easiest way is to put some kind of identifier in the file name itself, i.e. the pattern argument when you create the FileHandler. Since these are instances of the same application, one way to distinguish them is by their process id, so you could make that part of the pattern. A better approach is to pass in an identifier through the command line and use that to make your filename. That way you control the files being created in some sense. Finally, if your application has some knowledge of why it's different from all the others, for example it connects to a particular database server, then you could just use that database server name as part of the filename.
EDIT: There does not seem to be any API to get the name of the file being used by a FileHandler. I would suggest looking into the logging extensions in x4juli (which ports a lot of the log4j functionality to the java.util.logging specs):
http://www.x4juli.org/
You should be able to substitute an instance of their FileHandler which provides a getFile() method:
http://www.x4juli.org/api/org/x4juli/handlers/FileHandler.html
Actually, you could do this much simpler by simply extending FileHandler yourself. For example...
MyFileHandler.java:
import java.io.IOException;
import java.util.logging.FileHandler;
public class MyFileHandler extends FileHandler {
protected String _MyFileHandler_Patern;
public MyFileHandler(String pattern) throws IOException {
_MyFileHandler_Patern = pattern;
}
public String getMyFileHandlerPattern() {
return _MyFileHandler_Patern;
}
}
DeleteMe.java:
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Logger;
public class DeleteMe {
public static void main(String[] args) throws IOException {
Logger log = Logger.getLogger(DeleteMe.class.getName());
MyFileHandler output = new MyFileHandler("output.log");
log.addHandler(output);
for (Handler handler : log.getHandlers()) {
if (handler instanceof MyFileHandler) {
MyFileHandler x = (MyFileHandler) handler;
if ("output.log".equals(x.getMyFileHandlerPattern())) {
System.out.println("found hanlder writing to output.log");
}
}
}
}
}
OK, I do have to say that FileHandler not providing a way to determine the log file is seriously dumb.
I wound up writing a function called "chooseFile()" which searches /tmp for the next available log file name and returns that file. You can then pass the name of that file into new FileHandler().
/**
* Utility: select a log file. File is created immediately to reserve
* its name.
*/
static public File chooseFile(final String basename) throws IOException {
final int nameLen = basename.length();
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
String[] logs = tmpDir.list(new FilenameFilter() {
public boolean accept(File d, String f) {
return f.startsWith(basename);
}
});
int count = 0;
if (logs.length > 0) {
for (String name : logs) {
int n = atoi(name.substring(nameLen));
if (n >= count) count = n + 1;
}
}
String filename = String.format("%s%d.log", basename, count);
File logFile = new File(tmpDir, filename);
logFile.createNewFile();
return logFile;
}
Here's my rather hacky way around it. It works for the default if you don't use any format strings, and should work if you use the g and u format strings in filename, but not the others.
public class FriendlyFileHandler extends FileHandler {
/***
* In order to ensure the most recent log file is the file this one owns,
* we flush before checking the directory for most recent file.
*
* But we must keep other log handlers from flushing in between and making
* a NEW recent file.
*/
private static Object[] flushLock = new Object[0];
private String pattern;
public FriendlyFileHandler(String pattern, int maxLogLengthInBytes, int count) throws IOException,
SecurityException {
super(pattern, maxLogLengthInBytes, count);
this.pattern = pattern;
}
/***
* Finds the most recent log file matching the pattern.
* This is just a guess - if you have a complicated pattern
* format it may not work.
*
* IMPORTANT: This log file is still in use. You must
* removeHandler() on the logger first, .close() this handler,
* then add a NEW handler to your logger. THEN, you can read
* the file.
*
* Currently supported format strings: g, u
*
* #return A File of the current log file, or null on error.
*/
public synchronized File getCurrentLogFile() {
synchronized(flushLock) {
// so the file has the most recent date on it.
flush();
final String patternRegex =
// handle incremental number formats
pattern.replaceAll("%[gu]", "\\d*") +
// handle default case where %g is appended to end
"(\\.\\d*)?$";
final Pattern re = Pattern.compile(patternRegex);
final Matcher matcher = re.matcher("");
// check all files in the directory where this log would be
final File basedir = new File(pattern).getParentFile();
final File[] logs = basedir.listFiles(new FileFilter() {
#Override
public boolean accept(final File pathname) {
// only get files that are part of the pattern
matcher.reset(pathname.getAbsolutePath());
return matcher.find();
}
});
return findMostRecentLog(logs);
}
}
private File findMostRecentLog(File[] logs) {
if (logs.length > 0) {
long mostRecentDate = 0;
int mostRecentIdx = 0;
for (int i = 0; i < logs.length; i++) {
final long d = logs[i].lastModified();
if (d >= mostRecentDate) {
mostRecentDate = d;
mostRecentIdx = i;
}
}
return logs[mostRecentIdx];
}
else {
return null;
}
}
#Override
public synchronized void flush() {
// only let one Handler flush at a time.
synchronized(flushLock) {
super.flush();
}
}
}

Categories