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).
Related
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.
Im currently working on a program and any time i call Products[1] there is no null pointer error however, when i call Products[0] or Products[2] i get a null pointer error. However i am still getting 2 different outputs almost like there is a [0] and 1 or 1 and 2 in the array. Here is my code
FileReader file = new FileReader(location);
BufferedReader reader = new BufferedReader(file);
int numberOfLines = readLines();
String [] data = new String[numberOfLines];
Products = new Product[numberOfLines];
calc = new Calculator();
int prod_count = 0;
for(int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if(data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
System.out.println(Products[prod_count].getName());
BigDecimal price = new BigDecimal(data[2]);
Products[prod_count].setPrice(price);
for(String dataSt : data)
{
if(dataSt.toLowerCase().contains("imported"))
{
Products[prod_count].setImported(true);
}
else{
Products[prod_count].setImported(false);
}
}
calc.calculateTax(Products[prod_count]);
calc.calculateItemTotal(Products[prod_count]);
prod_count++;
This is the output :
imported box of chocolates
1.50
11.50
imported bottle of perfume
7.12
54.62
This print works System.out.println(Products[1].getProductTotal());
This becomes a null pointer System.out.println(Products[2].getProductTotal());
This also becomes a null pointer System.out.println(Products[0].getProductTotal());
You're skipping lines containing "input".
if(data[i].contains("input")) {
continue; // Products[i] will be null
}
Probably it would be better to make products an ArrayList, and add only the meaningful rows to it.
products should also start with lowercase to follow Java conventions. Types start with uppercase, parameters & variables start with lowercase. Not all Java coding conventions are perfect -- but this one's very useful.
The code is otherwise structured fine, but arrays are not a very flexible type to build from program logic (since the length has to be pre-determined, skipping requires you to keep track of the index, and it can't track the size as you build it).
Generally you should build List (ArrayList). Map (HashMap, LinkedHashMap, TreeMap) and Set (HashSet) can be useful too.
Second bug: as Bohemian says: in data[] you've confused the concepts of a list of all lines, and data[] being the tokens parsed/ split from a single line.
"data" is generally a meaningless term. Use meaningful terms/names & your programs are far less likely to have bugs in them.
You should probably just use tokens for the line tokens, not declare it outside/ before it is needed, and not try to index it by line -- because, quite simply, there should be absolutely no need to.
for(int i = 0; i < numberOfLines; i++) {
// we shouldn't need data[] for all lines, and we weren't using it as such.
String line = reader.readLine();
String[] tokens = line.split("(?<=\\d)\\s+|\\s+at\\s+");
//
if (tokens[0].equals("input")) { // unclear which you actually mean.
/* if (line.contains("input")) { */
continue;
}
When you offer sample input for a question, edit it into the body of the question so it's readable. Putting it in the comments, where it can't be read properly, is just wasting the time of people who are trying to help you.
Bug alert: You are overwriting data:
String [] data = new String[numberOfLines];
then in the loop:
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
So who knows how large it is - depends on the success of the split - but your code relies on it being numberOfLines long.
You need to use different indexes for the line number and the new product objects. If you have 20 lines but 5 of them are "input" then you only have 15 new product objects.
For example:
int prod_count = 0;
for (int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if (data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
// etc.
prod_count++; // last thing to do
}
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.
I am working with matrix in java. ( another story :) )
I want to read a CSV file and store it in a variable. I will manipulate values then again store it in CSV file. I used STRING as data type. But if CSV file has like 500 columns. It kill my program speed :(. I think this is not good data type. Which data type I can use to temporary store LONG TEXT?
If my question is not clear please ask questions. I will explain.
Thanks
P.S: I am reading one line and storing it in variable like this
String str;
str += read line by line from CSV;
here is the loop
String reduceM="";
for(int kk=0;kk<W2.getRowDimension();kk++){
for(int jj=0;jj<W2.getColumnDimension();jj++){
reduceM += Double.toString(reduceMatrix[kk][jj]);
}
System.out.println("\r\n");
}
Use a StringBuilder (or StringBuffer if you're using Java 1.5 or older):
StringBuilder builder = new StringBuilder();
for (int kk = 0; kk<W2.getRowDimension(); kk++) {
for(int jj = 0; jj < W2.getColumnDimension(); jj++) {
builder.append(reduceMatrix[kk][jj]);
}
}
This will avoid it creating a new (and increasingly long) string for each iteration of the two loops.
However, there are no commas or line-breaks in this code - I suspect you actually want something like this:
StringBuilder builder = new StringBuilder();
for (int kk = 0; kk < W2.getRowDimension(); kk++) {
for (int jj = 0; jj < W2.getColumnDimension(); jj++) {
builder.append(reduceMatrix[kk][jj])
.append(",");
}
builder.append("\n"); // Or whatever line terminator you want
}
Note that that will leave an extra comma at the end of each row - let me know if you want ideas of how to remove that.
See this article for why this could make a huge improvement to your running time. (Note that it's an old article, talking about StringBuffer rather than StringBuilder - the latter is just an unsynchronized version of the former.)
Use the 'StringBuffer' class for concatenations. It is much more efficient.
Take a look at this article for an explanation: here
EDIT - Sorry I did not see this was already answered
Prefer StringBuilder, there is a big difference in performance compared to the string concatenation(+).
In addition to the skeet's great answer; dont write to system.out if its not necessary, or if you want to write to console use buffers or write when loop finishes. It makes your program cumbersome because each time it is encountered in the loop System.out stream opens writes flushes and closes.
public boolean catDog(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
String sub = str.substring(i, i+1);
if (sub.equals("cat") && sub.equals("dog"))
count++;
}
return count == 0;
}
There's my code for catDog, have been working on it for a while and just cannot find out what's wrong. Help would be much appreciated!*/
EDIT- I want to Return true if the string "cat" and "dog" appear the same number of times in the given string.
One problem is that this will never be true:
if (sub.equals("cat") && sub.equals("dog"))
&& means and. || means or.
However, another problem is that your code looks like your are flailing around randomly trying to get it to work. Everyone does this to some extent in their first programming class, but it's a bad habit. Try to come up with a clear mental picture of how to solve the problem before you write any code, then write the code, then verify that the code actually does what you think it should do and that your initial solution was correct.
EDIT: What I said goes double now that you've clarified what your function is supposed to do. Your approach to solving the problem is not correct, so you need to rethink how to solve the problem, not futz with the implementation.
Here's a critique since I don't believe in giving code for homework. But you have at least tried which is better than most of the clowns posting homework here.
you need two variables, one for storing cat occurrences, one for dog, or a way of telling the difference.
your substring isn't getting enough characters.
a string can never be both cat and dog, you need to check them independently and update the right count.
your return statement should return true if catcount is equal to dogcount, although your version would work if you stored the differences between cats and dogs.
Other than those, I'd be using string searches rather than checking every position but that may be your next assignment. The method you've chosen is perfectly adequate for CS101-type homework.
It should be reasonably easy to get yours working if you address the points I gave above. One thing you may want to try is inserting debugging statements at important places in your code such as:
System.out.println(
"i = " + Integer.toString (i) +
", sub = ["+sub+"]" +
", count = " + Integer.toString(count));
immediately before the closing brace of the for loop. This is invaluable in figuring out what your code is doing wrong.
Here's my ROT13 version if you run into too much trouble and want something to compare it to, but please don't use it without getting yours working first. That doesn't help you in the long run. And, it's almost certain that your educators are tracking StackOverflow to detect plagiarism anyway, so it wouldn't even help you in the short term.
Not that I really care, the more dumb coders in the employment pool, the better it is for me :-)
choyvp obbyrna pngQbt(Fgevat fge) {
vag qvssrerapr = 0;
sbe (vag v = 0; v < fge.yratgu() - 2; v++) {
Fgevat fho = fge.fhofgevat(v, v+3);
vs (fho.rdhnyf("png")) {
qvssrerapr++;
} ryfr {
vs (fho.rdhnyf("qbt")) {
qvssrerapr--;
}
}
}
erghea qvssrerapr == 0;
}
Another thing to note here is that substring in Java's built-in String class is exclusive on the upper bound.
That is, for String str = "abcdefg", str.substring( 0, 2 ) retrieves "ab" rather than "abc." To match 3 characters, you need to get the substring from i to i+3.
My code for do this:
public boolean catDog(String str) {
if ((new StringTokenizer(str, "cat")).countTokens() ==
(new StringTokenizer(str, "dog")).countTokens()) {
return true;
}
return false;
}
Hope this will help you
EDIT: Sorry this code will not work since you can have 2 tokens side by side in your string. Best if you use countMatches from StringUtils Apache commons library.
String sub = str.substring(i, i+1);
The above line is only getting a 2-character substring so instead of getting "cat" you'll get "ca" and it will never match. Fix this by changing 'i+1' to 'i+2'.
Edit: Now that you've clarified your question in the comments: You should have two counter variables, one to count the 'dog's and one to count the 'cat's. Then at the end return true if count_cats == count_dogs.