Java Applet Not Finding File [duplicate] - java

I have an applet that I am trying to make read a file. It throws an exception, but I am passing it the correct path so I am not sure where I am going wrong. I am using this to read numbers and use those numbers to change a multidimensional array, if you were wondering. Heres the code:
public class Save {
public void loadSave(File loadPath) {
try {
Scanner loadScanner = new Scanner(loadPath);
while(loadScanner.hasNext()){
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].groundID = loadScanner.nextInt();
System.out.println(loadScanner.nextInt());
}
}
for(int y = 0; y < Screen.room.block.length;y++){
for(int x = 0; x < Screen.room.block[0].length;x++){
Screen.room.block[y][x].airID = loadScanner.nextInt();
}
}
}
loadScanner.close();
} catch (Exception e) { e.printStackTrace();}
}
}
How I access it:
save.loadSave(new File(frame.getClass().getResource("mission1.tdm").toString()));
Ok, I used the edited code up above and it still says that it cannot find the file, even though the error spits out the exact path that it is in.

Related

Java - I need to print this string of characters to a string I can use out of loop

I have been buried in this assignment for 2 days chasing down rabbit holes for possible solutions. I am beginner Java, so I am sure this shouldn't be as difficult as I am making it.
I trying to program the infamous Java Bean Machine... My professor want the Class Path to return a String Variable that only holds "R" "L" . to represent the path of the dropped ball.
Each ball should have its own Path... I can get the path... but I can not get the path to print in a string outside of the for/if statement.
Here are his instructions... in case you can see if I am interpreting this incorrectly.
Please help!! Thank you in advance for sifting through this....
my code so far ******** i have updated the code to reflect the suggestions.. Thank you... ***************** New problem is it repeats the series of letters in a line... I only need a string of 6 char ....(LRLLRL)
public class Path {
StringBuilder myPath;
public Path() {
myPath = new StringBuilder();
}
void moveRight() {
myPath.append("R");
}
void moveLeft() {
myPath.append("L");
}
public void fallLevels(int levels) {
levels = 6;
for (int i = 0; i < (levels); i++) {
if (Math.random() < 0.5) {
this.moveRight();
} else {
this.moveLeft();
}
}
}
public String getPath() {
System.out.print(myPath.toString());
return myPath.toString();
}
}
}
******Thank you all.. this class now returns the correct string for one ball...***************
here is my code so far for multiple balls... I can get a long continuous string of 6 character sequences... I need each sequence to be a searchable string...I am not sure if I need to alter the Path class or if its something in the simulateGame() method. I think I can take it after this hump... Thank you again....
public class BeanMachine {
int numberOfLevels;
int[] ballsInBins;
Path thePath = new Path();
public BeanMachine(int numberOfLevels) {
this.numberOfLevels = 6;
ballsInBins = new int[this.numberOfLevels + 1];
// this.numberOfLevels +
}
public void simulateGame(int number) {
//looping through each ball
for (int i = 0; i < numberOfLevels -1; i++) {
thePath.fallLevels(0);
}
thePath.getPath().toString();
}
*** this isn't the entire code for this class... I have to get this method correct to continue....
Problem with your code:
if (Math.random() < 0.5) {
**loop = this.myPath = "R";**
} else {
**loop = this.myPath ="L";**
}
Change this to:
if (Math.random() < 0.5) {
**loop = this.myPath + "R";**
} else {
**loop = this.myPath + "L";**
}
Just added ** to highlight where there is wrong in your code

How to delete/move this line of code in NetBeans

I just have this one line of code:
}
with gray highlight on it. I cannot delete/move it, basically I cannot do anything to it. Please tell me why it is like that and how to delete it?
Thanks
for (int iPlay=0; iPlay<1; iPlay++)
{
for (int iCount=0;iCount<NonConference.length;iCount++)
{
for (int iCount2 = iCount+1; iCount2 < Conference.length; iCount2++)
{
int HomeScore = 0;
int OppScore = 0;
while (HomeScore==OppScore){
HomeScore=RandomNumber.nextInt(100);
OppScore=RandomNumber.nextInt(100);
}
if(HomeScore>OppScore)
{Conference[iCount].wins ++;
NonConference[iCount2].losses++;
}
else
{Conference[iCount].losses ++;
NonConference[iCount2].wins++;
}
}}
} //THIS IS IT!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Output
Team1name.setText(Conference[0].team);
Team2name.setText(Conference[1].team);
Team3name.setText(Conference[2].team);
}
Edit the .java class in notepad and remove the //GEN - END code from the file. Now the code should be unprotected in NETBEANS

Thread terminating when running a function in java

I am programing a midi maker that you can make a song through the console (and later a window) but I'm having a thread issue. When I want the song to start, the thread starts but it doesn't run the function that has the song player. I copy and pasted the base code from a working project and I cant figure out why it is not running. IT prints "setting up" but not "running". Here is my code for the function:
public void songStart() throws InterruptedException {
int temp;
channelVolume = new int[channelNotes.length][channelNotes[0].length];
if (channelNotes.length < userChannels.length) {
temp = channelNotes.length;
} else {
temp = userChannels.length;
}
for (int j = 0; j < userChannelNotesNumLongest; j++) {
for (int i = 0; i < temp; i++) {
if (channelNotes[i][j] == r) {
channelVolume[i][j] = 0;
} else if (advanced == false){
channelVolume[i][j]=50;
}
}
}
System.out.println("running");
for (int i = 0; i < temp; i++) {
for (int j = 0; j < userChannelNotesNumLongest; j++) {
noteOn(userChannels[i],channelNotes[i][j],channelVolume[i][j]);
Thread.sleep(interval);
noteOff(userChannels[i],channelNotes[i][j]);
}
}
}
And this is the code for the thread:
public class SongThread extends Thread {
public void run(){
try {
Main.song.songStart();
} catch (InterruptedException e) { }
}
}
Here is were the code runs the thread (i have a print in there that does print)
if (userInput.equals("start")) {
System.out.println("setting up");
SongThread thread = new SongThread();
thread.start();
}
Note: everything works fine until the thread tries to run the function, then it just stops running it. Also, it is the same base code in the other project that works fine. The function that is displayed is in a class instance in Main called song. And I don't get an error from the catch. Keep in mind that I copy and pasted the code from a working project and the only thing different is that it is not static and runs the instance from the Main class
I have tried making the songStart function static with everything inside as well. I have used all the combinations of try / catch an d throws exceptions in the thread and the function (where the thread didn't have a try / catch or throws and where the function has a try / catch or a throws). the way I have it in my working project is a throws in the function and a try / catch in the thread.

Printing ArrayList of 2D arrays in a specific format

I'm trying to save an ArrayList to a text file in a particular format. It's in the correct format but it only prints out the color of one element in the ArrayList of blocks. I know the problem lies with the getBlockColor() method, what's the best way to implement this method? Here's what I've got so far.
This is the method that is in the class with the ArrayList of frames.
public void saveFrames(String fileName) {
System.out.println("**method save writes data back to a file "
+ fileName);
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(fileName)));
outfile.println(frames.size());
outfile.println(Frame.getCOLUMNS());
for (Frame f : frames) {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
Color a = f.getBlockColor();
if (a.equals(Color.white)) {
outfile.print("w");
}
if (a.equals(Color.orange)) {
outfile.print("o");
}
if (a.equals(Color.red)) {
outfile.print("r");
}
if (a.equals(Color.yellow)) {
outfile.print("y");
}
if (a.equals(Color.green)) {
outfile.print("g");
}
if (a.equals(Color.blue)) {
outfile.print("b");
}
}
outfile.println("");
}
}
outfile.close();
}
catch (IOException e) {
System.out.println("file not found try again");
}
}
This is the code from the frame that is supposed to get the color of the blocks.
public Color getBlockColor() {
for (int ROWS = 0; ROWS < 20; ROWS++) {
for (int COLUMNS = 0; COLUMNS < 20; COLUMNS++) {
blockColor = blocks[ROWS][COLUMNS].getBackground();
}
}
return blockColor;
}
I think you made a small mistake in getting the block color.
I guess you were supposed to return the color for a specific row and column, like this:
public Color getBlockColor(int row, int column) {
return blocks[row][column].getBackground();
}

Java - NullPoinerException Array of objects [closed]

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.
Can't figure this out, I've created a simple class of coordinates to hold x and y ints. In another class I have a global array of Coordinates declared called "ords". In my loop I'm adding Coordinates. When trying to use method getX() and getY() from the Coordinates class in my getaction method, I get a null pointer exception. I'm sure the objects are not null, but I still can't figure out whats going wrong. Any help appreciated.
import java.util.*;
import org.w2mind.net.*;
import java.io.Serializable;
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
int currentX;
int currentY;
//====== Mind must respond to these methods: ==========================================================
// newrun(), endrun()
// getaction()
//======================================================================================================
public void newrun() throws RunError
{
}
public void endrun() throws RunError
{
}
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
{
for(int z = 0; z < 12; z++)
{
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
}
else if(surroundings[z][i]==4){
ords[n]= new Coordinates(z,i);
n++;
}
System.out.print(z+" , "+i+": "+surroundings[z][i]);
System.out.println();
counter++;
}
}
}
public Action getaction ( State state )
{
String s = state.toString();
String[] x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192];
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
{
surround[counter] = Integer.parseInt(x[i]);
counter++;
}
formTwoDimmensional(surround);
int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
{
response[i] = Integer.parseInt ( x[i] );
}
System.out.println("Current position: "+currentX+" ,"+currentY);
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
if(coalX != 0 && coalY !=0)
{
if(coalX>currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
else if(coalX<currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
}
String a = String.format ( "%d", act );
return new Action ( a );
}
}
class Coordinates implements Serializable
{
private int x;
private int y;
public Coordinates(int x1, int y1)
{
x=x1;
y=y1;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Error is as follows:
java.lang.NullPointerException
at ConorsMind.getaction(ConorsMind.java:146)
The error is stemming from the following two lines:
int coalX=ords[0].getX();
int coalY=ords[0].getY();
I am calling formTwoDimensional() and its working perfectly, the ords objects are being created successfully and are not null as testing with System.out.println(ords[n].getX()) is printing the expected result when placed in my else if(surroundings[z][i]==4) block.
You need to make sure that you're calling formTwoDimensional(). If you are indeed, then it's likely that you're not ever getting into your else if block in the nested for loop, and hence ords[0] is never actually being set, so when you try to access it, it's null.
The other thing to do, if you don't want to post the rest of your code, is to add some more debugging code. See below the boolean zero_pos_set. But make sure that you see the print "Zero pos set" before your program crashes. My bet is that you don't.
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
boolean zero_pos_set = false;
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++) {
for(int z = 0; z < 12; z++) {
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
} else if(surroundings[z][i]==4) {
zero_pos_set = true;
ords[n]= new Coordinates(z,i);
n++;
}
counter++;
}
}
}
public Action getaction ( State state ) {
if(zero_pos_set) {
System.out.println("Zero pos set!");
}
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
return new Action ( a );
}
}
Based on all of the debugging information posted within this thread, it seems that in your getaction() function, you're being passed some state, that doesn't contain 4.
When you parse this information and pass it to formTwoDimensional(), you will never reach the else if block, and so ords[0], or any other ords[n], will never be set.
As a result, when you try to access ords[0] back in your getaction() function, you actually get null, and hence your NullReferenceException.
It's an order of operations issue.
If you never make a call to formTwoDimmensional(), you'll never initialize anything inside of your array. Be sure you're calling that first.
The actual NPE happens when you attempt to call coalX=ords[0].getX();, which won't work if ords[0] is null.

Categories

Resources