Optimizing Java Code Snippet - java

I;m trying to shorten code on a program I'm coding and the code I need advice on shortening is this part:
imgRunM[0] = toolkit.createImage(imageURL11);
imgRunM[1] = toolkit.createImage(imageURL12);
imgRunM[2] = toolkit.createImage(imageURL13);
imgRunM[3] = toolkit.createImage(imageURL14);
imgRunM[4] = toolkit.createImage(imageURL15);
imgRunM[5] = toolkit.createImage(imageURL16);
I was thinking it could be written as a loop, just not sure how to write it correctly.
I tried this:
for (int x=1; x<7;x++)
imgRunM[x-1] = toolkit.createImage(imageURL1+x);
It did not error out but when I ran the program, the image did not appear so I'm not really sure what happened.
If anyone has any suggestions I would appreciate it.

I'd suggest making an array of imageURL's also, instead of having a new variable name for each one. Then you could do this:
for (int i = 0; i <= 5; i++) {
imgRunM[i] = toolkit.createImage(imageURL[i+11]);
}
Not sure why you have the +11 offset, but I kept it intact.

Related

java.lang.ArrayIndexOutOfBoundsException: length=1; index=2 caused by IF condition

Good day everyone
Im creating application and I need to get some data from text. For this reason i was creating Arraylist, which will be filled up by needed data, was from splitted before string "gh2[]".I was using IF condition to determine required data(gh2[i].matches("[0-9]+]). After filling Array, I was converting Array to a string, by StringBuilder, after this string was splitted.
My problem is when I want to call back for examble second value from splitted String Im getting this error: java.lang.ArrayIndexOutOfBoundsException: length=1; index=2.
I dont understand reason of this error becouse when Im checking, size of the Array is showing 23, when Im calling back string before splitting I can see that is filled up by required data. I was trying to change IF condition like for examble giving negation, then everything is working fine but Array is not filled up by data which I need. Please for advice how to fix this problem. gh2 This my
Here is my program, this is my first program in Android Studio.
ArrayList<String> listawynikow = new ArrayList<String>(gh2.length);
for (int i = 0; i < gh2.length; i++) {
if (gh2[i].matches("[0-9]+")) {
listawynikow.add(gh2[i]);
}
}
StringBuilder sb2 = new StringBuilder();
for (int j = 0; j < listawynikow.size(); j++) {
sb2.append(listawynikow.get(j)).append(";").append("\n");
}
String wyniki1 = sb2.toString();
String[] WYNIKI = wyniki1.split(";");
OK, finally I fix the problem by this.
for(i2=0; i2<gh2.length;i2++) {
listawynikow.add(gh2[i2]); }
for(int j2=0; j2<listawynikow.size();j2++){
if (!gh2[j2].matches("[0-9]+")){
listawynikow.remove(gh2[j2])
Thanks everybody for help and fingers crossed for my problem.

Java StingIndexoutOfBounds

I keep getting an error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 10
at java.lang.String.charAt(Unknown Source)
at Field.setLocations(Field.java:175)
at Field.(Field.java:39)
at SeaBattle.onePlayer(SeaBattle.java:76)
at SeaBattle.play(SeaBattle.java:36)
at MainClass.main(MainClass.java:7)
public void setLocations() {
Random rand = new Random();
ArrayList<String> locationToSet = new ArrayList<String>();
ArrayList<String> temp = null;
int let, num, incl, incn;
String alpha = "ABCDEFGHIJ";
boolean worked;
for (int i = 0; i < ships.size(); i++) {
worked = false;
start: while (!worked) {
locationToSet.clear();
worked = true;
let = rand.nextInt(9);
num = 1 + rand.nextInt(9);
if (num % 2 == 0) {
//num even or odd
incl = 1;
incn = 0;
} else {
incl = 0;
incn = 1;
}
for (int j = 0; j < ships.get(i).getLength(); j++) {
String loc = "" + alpha.charAt(let) + num;
let += incl;
num += incn;
for (int t = 0; t < ships.size(); t++) {
if (t != i) {
temp = ships.get(t).getLocation();
if (temp.contains(loc)) {
worked = false;
continue start;
}
}
}
locationToSet.add(loc);
}
ships.get(i).setLocation(locationToSet);
}
}
}
the line 175 is
for (int j = 0; j < ships.get(i).getLength(); j++) {
I have no idea why I get this error. If I change the < in == then I don't get the error. But then it won't give my objects their locations.
There are already many resources on this in Stack Overflow which can be found with Googling, but I think the larger issue here is you need to understand how exceptions and errors are telling you something went wrong, and Java can't do what you told it to do because it's not able to.
Looking at the error you posted. That is a stacktrace. You'll see a ton of this in programming, you might hate seeing them but they're your friend, because without them, we can't tell if our program ran properly or not. You can read it from bottom up right after it tells it that an exception of java.lang.StringIndexOutOfBoundsException occurred.
Here's how to read your error from bottom up:
at MainClass.main(MainClass.java:7)
This means that your error started when Java was at this line doing all the function calls. Line 7 of MainClass.java, which jumps to
at SeaBattle.play(SeaBattle.java:36)
That's line 36 in your SeaBattle java. Which goes to
at SeaBattle.onePlayer(SeaBattle.java:76)
to
at Field.(Field.java:39)
to
at Field.setLocations(Field.java:175)
and finally.
at java.lang.String.charAt(Unknown Source)
The last line tells you when you did String.charAt it tried to read from an unknown source, which based on the Exception it gave you, meant that it happened at index 10, possibly meaning your string was only up to 9 characters. (As a guess you probably did a for-loop and tried reading the wrong index)
A good approach is to look at that line and see if you can figure out what's wrong. (Double clicking on the exceptions in IDEs usually brings focus to that point).
If that didn't work..
Use the debugger
If you use Eclipse or Netbeans to write java, they all have a debugger that assists you with well, debugging your code. Set a breakpoint at line 7 of MainClass, or any of those lines in that stack trace and run the debugger to step through your code. Here's a great tutorial on how to do that. Manually stepping through your code will let you see exactly what went wrong, that way you can find your problem. Good luck with your homework assignment, this is a good one to learn about for-loops and reading arrays, go ask your TA if you can't figure out the bug, we're more helpful in person.

Changing an array attempt

I posted this question up earlier and it was pretty much a lazy post as I didn't provide the code I had and as a result got negged pretty badly. Thought I'd create a new one of these ....
I have an array dogArray which takes ( name, secondname, dogname )
I want to be able to change the dogname:
here's my attempt :
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
String namgeChange = rp.next(); {
for (int i = 0; i < dogArray.length; i++){
for (int j = 0; j < dogArray[i].length; j++){
if (dogArray[i][j] == name){
dogArray[i][j] = nameChange;
}
}
}
}
For a start it doesn't like the fact I've used ' name ' although it is defined in the dogArray. I was hoping this would read input so that users are able to change 'name' to whatever they input. This will change the value of name in the array.
Do you guys think I'm getting anywhere with my method or is it a pretty stupid way of doing it?
Only one loop is necessary, also move your call to next.
public void changeName(Entry [] dogArray) {
Scanner rp = new Scanner(System.in);
for (int i = 0; i < dogArray.length; i++){
String nameChange = rp.next(); {
if(!dogArray[i].name.equals(nameChange)){
dogArray[i].name = nameChange;
}
}
}
You might want to make this function static as well and use accessors and mutators to change and get the name. Might want to tell the user what you want them to type as well. Also there is no point in testing if the name changed, if it changed then set it, if it didnt change then set it (it doesnt hurt). Just get rid of if and keep the code inside.

Play sound directly from byte array - Java

I'm trying to play a sound that is stored as a byte-array using the following method:
byte[] clickSamples = getAudioFileData("sound.wav");
ByteBuffer buffer = ByteBuffer.allocate(bufferSize*2);
int tick = 0;
for (int i = 0; i < clickSamples.length; i++) {
buffer.putShort((short) clickSamples[i]);
tick++;
if (tick >= bufferSize/SAMPLE_SIZE) {
line.write(buffer.array(), 0, buffer.position());
buffer.clear();
tick = 0;
}
}
It's kind of hard to explain what's going wrong. I'm getting a sound but it's only like a "swoosh"-kind of noise.
I want to use this method with the byte-buffer and so on because my whole application is built around it. Using Clip or AudioInputStream is not really an option.
So I guess my question is:
How can I play sound directly from my byte-array using a byte-buffer?
Thank you for your help!
I've managed to make it work. Here is my new code:
int tick = 0;
for (int i = 0; i < clickSamples.length; i++) {
tick++;
if (tick >= bufferSize/SAMPLE_SIZE) {
line.write(clickSamples, i-tick+1, tick);
buffer.clear();
tick = 0;
}
}
This may seem like a complicated way of playing sound just like with AudioInputStream but now I can do calculations on each tick++ and by doing that I can intervene to exact times if I need to.
If this sounds silly and there is an easier way of doing this, please let me know.
Also, the reason it sounded so distorted is that it seems like ByteBuffer drastically changed my sample-values. For what reason I don't know. If anybody knows, please let me know!
Thank you. :)

Finding string from the next line of an ArrayList

I have this code, it should find a pre known method's name in the chosen file:
String[] sorok = new String[listaZ.size()];
String[] sorokPlusz1 = new String[listaIdeig.size()];
boolean keresesiFeltetel1;
boolean keresesiFeltetel3;
boolean keresesiFeltetel4;
int ind=0;
for (int i = 0; i < listaZ.size(); i++) {
for (int id = 0; id < listaIdeig.size(); id++) {
sorok = listaZ.get(i);
sorokPlusz1 = listaIdeig.get(id);
for (int j = 0; j < sorok.length; j++) {
for (int jj = 1; jj < sorok.length; jj++) {
keresesiFeltetel3 = (sorok[j].equals(oldName)) && (sorokPlusz1[id].startsWith("("));
keresesiFeltetel4 = sorok[j].startsWith(oldNameV3);
keresesiFeltetel1 = sorok[j].equals(oldName) && sorok[jj].startsWith("(");
if (keresesiFeltetel1 || keresesiFeltetel3 || keresesiFeltetel4) {
Array.set(sorok, j, newName);
listaZarojeles.set(i, sorok);
}
}
System.out.println(ind +". index, element: " +sorok[j]);
}
ind++;
}
}
listaZ is an ArrayList, elements spearated by '(' and ' ', listaIdeig is this list, without the first line (because of the keresesifeltetel3)
oldNameV3 is: oldName+ ()
I'd like to find a method's name if this is looking like this:
methodname
() {...
To do this I need the next line in keresesifeltetel 3, but I can't get it working properly. It's not finding anything or dropping errors.
Right now it writes out the input file's element's about 15 times, then it should; and shows error on keresesifeltetel3, and:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
I think your problem is here: sorokPlusz1[id]. id does not seem to span sorokPlusz1's range. I suspect you want to use jj and that jj should span sorokPlusz1's range instead of sorok's and that sorok[jj].startsWith("(") should be sorokPlusz1[jj].startsWith("(").
But note that I'm largely speculating as I'm not 100% sure what you're trying to do or what listaZ and listaIdeig look like.
You're creating sorok with size = listaZ's size, and then you do this: sorok = listaZ.get(i);. This is clearly not right. Not knowing the exact type of listaZ makes it difficult to tell you what's wrong with it. If it's ArrayList<String[]>, then change
String[] sorok = new String[listaZ.size()]; to String[] sorok = null; or String[] sorok;. If it's ArrayList<String> then you probably want to do something more like sorok[i] = listaZ.get(i);
Now for some general notes about asking questions here: (with some repetition of what was said in the comments) (in the spirit of helping you be successful in getting answers to questions on this site).
Your question is generally unclear. After reading through your question and the code, I still have little idea what you're trying to do and what the input variables (listaZ and listaIdeig) look like.
Using non-English variable names makes it more difficult for any English speaker to help. Even changing sorok to array and keresesiFeltetelX to bX would be better (though still not great). Having long variable names that aren't understandable makes it much more difficult to read.
Comment your code. Enough comments (on almost every line) makes it much easier to understand your code.
Examples. If you have difficulty properly explaining what you want to do (in English), you can always provide a few examples which would assist your explanation a great deal (and doing this is a good idea in general). Note that a good example is both providing the input and the desired output (and the actual output, if applicable).

Categories

Resources