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.
Related
A couple days ago I started learning Java and I implemented an algorithm which outputs all results of the MU-puzzle over a certain amount of iterations.
The code worked perfectly fine until I decided to make it so that you have to enter the amount of iterations through a JOptionPane window.
When I tried to import javax.swing.JOptionPane, that didn't work, so I looked up a tutorial, which has helped me before in that matter, however, somehow it didn't work this time (this is the tutorial in case you're curious: https://www.youtube.com/watch?v=GBzwSf8bEdQ).
Or I guess I should really say that it did fix the issue of import javax.swing.JOptionPane not being recognized by Eclipse (i.e. the red, squiggly line underneath it is gone).
But now whenever I try and access any member variables/functions of JOptionPane the program gives me an error and Intellisense doesn't even show the them in the first place, all it shows is class: Class<javax.swing.JOptionPane>.
Now all that happens when I try to compile my code is that I get this error message (even if I revert it back to its previously functional state):
So right now this is what my package (if that's the right term for it) looks like:
This is my code (again please note that I'm a beginner so it's not perfect)
This version is the one with JOptionPane:
(all that was different in the other version that worked (but doesn't anymore), was that the JOptionPane line is missing, the function miuExecute() did not exist and the code inside miuExecute() was put directly into the main function with iterations being just a fixed positive integer)
package miuSystem;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
miuExecute();
}
static void miuExecute() {
int iterations = JOptionPane.showInputDialog("Enter the amount of iterations you'd like to perform");
String input = "MI";
ArrayList<String> res = new ArrayList<String>();
ArrayList<String> miuIterations = new ArrayList<String>();
miuIterations.add(input);
for (int u = 0; u < iterations; u++) {
for(int q = 0; q < miuIterations.size(); q++) {
res.add(rule1(miuIterations.get(q)));
res.add(rule2(miuIterations.get(q)));
res.add(rule3(miuIterations.get(q)));
res.add(rule4(miuIterations.get(q)));
}
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res.size(); j++) {
if (j == i) {continue;}
else if (res.get(i).equals(res.get(j))) {
res.remove(i);
i--;
break;
}
}
}
System.out.println("Iteration #"+(u+1)+":");
System.out.println(res);
System.out.println();
miuIterations.clear();
for(String s : res) {
miuIterations.add(s);
}
res.clear();
}
}
static String rule1(String input) {
if (input.charAt((input.length())-1) == 'I') {
return input+"U";
}
else {
return input;
}
}
static String rule2(String input) {
String copy = "";
for (int i = 1; i<input.length(); i++)
{
copy = copy + input.charAt(i);
}
return input+copy;
}
static String rule3(String input) {
return input.replace("III", "U");
}
static String rule4(String input) {
return input.replace("UU","");
}
}
As already stated above, I tried following this tutorial (https://www.youtube.com/watch?v=GBzwSf8bEdQ) but it didn't work.
Googling my problem(s) (both on and off of StackOverflow) also yielded either no result at all / results that I don't understand yet and would take too long to understand instead of just asking or results that didn't help me.
Edit: as requested here is what I think was meant by "show us the contents of your module-info.java" (if not please just tell what else you need) the part of the image thats censored is obv. just my name, which i don't like.
enter image description here
I've written code for a foobar challenge that works in my IDE but not in the solutions file provided by foobar. Also, is there anyway to show the output even if the test fails? Possibly to with it being a static method or the input being {1, 2, 3, 4} whereas mine is working with new int {1,2,3,4,5}? My code is:
public static int solution(int[] l) {
List<Integer> numberList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
while (true) {
StringBuilder number = new StringBuilder();
int i = 0;
while (i < numberList.size()) {
number.append(numberList.get(i));
i++;
}
List<Integer> startingList = Arrays.stream(l).boxed().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
int testValue = numberList.size();
for (Integer integer : numberList) {
if (startingList.contains(integer)) {
startingList.remove(integer);
testValue--;
}
}
if (testValue == 0) {
int f = 0;
int total = 0;
while (f < numberList.size()) {
total = total + numberList.get(f);
f++;
}
if (total % 3 == 0) {
StringBuilder answer = new StringBuilder();
int c = 0;
while (c < numberList.size()) {
answer.append(numberList.get(c));
c++;
}
return Integer.parseInt(answer.toString());
}
}
Integer nextNumber = Integer.parseInt(number.toString()) - 1;
String[] stringArray = valueOf(nextNumber).split("");
numberList = new ArrayList<>();
for (String s : stringArray) {
numberList.add(Integer.parseInt(s));
}
}
}
Pretty rubbish but it does the job (at least in my IDE!)
As mentioned in a comment on the question, you should undoubtedly give some more context for your questions (since it is pretty unclear what your code is intended to do). I'm pretty sure I've inferred the actual question from context though, and I can suggest a couple of problems. In short (and a pretty good assumption for coding in general) the issue is not the environment running your code incorrectly, but rather your code having missed bugs due to lack of comprehensive testing. If you had presented a number of sample inputs and results I would guess you would have seen that your solution does not work locally.
The Java List.remove() method takes an index rather than a value to be removed (https://docs.oracle.com/javase/8/docs/api/java/util/List.html). The way it is used in your sample will result in throwing exceptions in a number of circumstances. Proper testing would have identified this (and will pick up most of your problems if fixed)
What happens if there is no solution? For example, an input of {1, 1} is going to get into a pretty messy state as the 'nextNumber' value slips below 0. You should know what the desired behavior is in this situation, and your tests should cover it before you try to upload a solution
This happened to me as well, but I then realized that my compilation was not successful because I have not imported the package that I am using at the top of the source code file like all java programs are write
public static int intersectionSizeMergeAndSort(studentList L1, studentList L2) {
int intersectionSize = 0;
int[] C = new int[L1.studentID.length+L2.studentID.length];
for(int i = 0; i<L1.studentID.length; i++){
C[i] = L1.studentID[i];
}
for(int i = 0; i<L2.studentID.length; i++){
C[i+L1.studentID.length] = L2.studentID[i];
}
Arrays.sort(C);
int pointer = 0;
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
if(C[pointer] = C[pointer+1]){
intersectionSize = intersectionSize + 1;
pointer = pointer + 2;
}
else {
pointer == pointer + 1;
}
return intersectionSize;
}
}
I have this algorithm I am writing for an assignment. Every time I compile my code, I get an error that I cannot understand in order to debug.
Error is as follows:
Error: /Users/nah/Desktop/studentList.java:137: operator < cannot be applied to int,<nulltype>
the error is pointing to the while loop statement
Not sure if this is directly related to the same error but your line
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
has mis-spelt the second "studentId" and should be "studentID"
while(pointer<((L1.studentID.length)+(L2.studentID.length))){
that is of course unless you happen to have two arrays defined for your studentID class, each with a different case.
I also agree with the other answers related to the "==" comparison operator, but you're telling us the error is related to the while statement
The only error I can see is:
if(C[pointer] = C[pointer+1]){
this should be:
if(C[pointer] == C[pointer+1]){
The following will not work in Java:
if (C[pointer] = C[pointer+1])
This is assignment, its type is int, it cannot be used in the if statement
While loop ? Ok. Debugging is done by simplifying expressions.
The only thing where we see < is the loop condition. Instead of
int pointer = 0;
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
do
int pointer = 0;
int len = ((L1.studentID.length)+(L2.studentId.length));
while(pointer< len){
If error again, simplify the error-raising expression.
I think that this question is mistitled. It is ** ambigous only because you do not attempt to localize it. Post a question only if "<" does not work for two integers. The current question title must be: "how do you debug Java programs?"
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).
I am a newbie Computer Science high school student and I have trouble with a small snippet of code. Basically, my code should perform a basic CLI search in an array of integers. However, what happens is I get what appears to be an infinite loop (BlueJ, the compiler I'm using, gets stuck and I have to reset the machine). I have set break points but I still don't quite get the problem...(I don't even understand most of the things that it tells me)
Here's the offending code (assume that "ArrayUtil" works, because it does):
import java.util.Scanner;
public class intSearch
{
public static void main(String[] args)
{
search();
}
public static void search()
{
int[] randomArray = ArrayUtil.randomIntArray(20, 100);
Scanner searchInput = new Scanner(System.in);
int searchInt = searchInput.nextInt();
if (findNumber(randomArray, searchInt) == -1)
{
System.out.println("Error");
}else System.out.println("Searched Number: " + findNumber(randomArray, searchInt));
}
private static int findNumber(int[] searchedArray, int searchTerm)
{
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
}
}
This has been bugging me for some time now...please help me identify the problem!
I don't know about the infinite loop but the following code is not going to work as you intended. The i++ can never be reached so i will always have the value 0.
for (int i = 0; searchedArray[i] == searchTerm && i < searchedArray.length; i++)
{
return i;
}
return -1;
You probably mean this:
for (int i = 0; i < searchedArray.length; i++)
{
if (searchedArray[i] == searchTerm)
{
return i;
}
}
return -1;
I don't know what is the class ArrayUtil (I can not import is using my Netbeans). When I try to change that line with the line int[] randomArray = {1 , 2, 3, 5, 7, 10, 1 , 5}; It works perfectly.
And you should change the loop condition. I will not tell you why but try with my array and you will see the bug soon. After you see it, you can fix it:)
There are 4 basic issues here.
1. Putting searchedArray[i] == searchTerm before i < searchedArray.length can result in an out-of-bounds exception. You must always prevent that kind of code.
2. Your intention seems to be the opposite of your code. Your method name implies finding a search term. But, your code implies that you want to continue your loop scan until the search term is not found, although your loop won't do that either. Think of "for (; this ;) { that } " as "while this do that".
3. Place a break point at the beginning of "search". Then, with a small array, step through the code line by line with the debugger and watch the variables. They don't lie. They will tell you exactly what's happening.
4. Please use a standard IDE and compiler, such as Eclipse and Sun's JDK 6 or 7. Eclipse with JDK 7 is a serious combination that doesn't exhibit a strange "infinite loop" as you describe above.