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?"
Related
I have built a method which compares objects attributes with user input int. The method then adds all the objects to an array(the assignment demands it to be an Array and not ArrayList). After its added I have a foor-loop which prints out a list of Results for an athlete(in user input), it prints out all results from one category and then another and so forth..
I keep getting a NullPointerException error on the last line which is a System.out.println. I have searched for an answer for hours, and read the NullPointerException posts here but cannot find the issue or solve it.
for (int x = 0; x < category.size(); x++) {
Category c = categories.get(x);
System.out.println("Result in " + c.categoryName() + " for " + matchedAthlete.surName() + " "
+ matchedAthlete.lastName() + ": ");
for (int i = 0; i < individarrayresult.length; i++) {
Result res = individarrayresult[i];
if (res.nameOfCategory().equals(c.categoryName())) {
System.out.println(res.categoryResult());
}
}
}
So the last line of code ( System.out.println ) gets the NullPointerException, I am desperete for help. Below is the Array filled with results from only 1 Athlete.
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If you have a NullPointerException on that row:
System.out.println(res.categoryResult());
The problem is in the method categoryResult because res is not null, otherwyse the previous test
if (res.nameOfCategory().equals(c.categoryName())) {
must throw the NullPointerException prior of the System.out.
So check the code of categoryResult() or post it.
Perhaps, as T.J. said, that the problem is not on that row but on the previous row and the NullPointerException is related to the value of res. Post the complete StackTrace and row lines of your code to be sure of that answer.
I think you're mistaken, I think you're getting the NPE one line earlier, on this line:
if (res.nameOfCategory().equals(c.categoryName())) {
And the reason you're getting it is there are nulls in your array, because of how you fill it:
Result[] individarrayresult = new Result[resultlist.size()];
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individarrayresult[i] = res;
}
}
If res.athleteStartNumber() == DSN is false, you never assign anything to individarrayresult[i], so that array entry keeps its null default.
How to fix it:
Build up a list of matching results:
List<> individResults = new Arraylist<Result>(resultlist.size());
for (int i = 0; i < resultlist.size(); i++) {
Result res = resultlist.get(i);
if (res.athleteStartNumber() == DSN) {
individResults.add(res);
}
}
...and then either use that list directly, or convert it to an array:
Result[] individarrayresult = individResults.toArray(new Result[individResults.size()]);
...and use the resulting array.
(You can also do the same with the nifty new streams stuff in the latest version of Java, but I'm not au fait with them...)
It's possible, of course, that you're getting the NPE on the line you said you are and that there are two problems, and it just happens you've been processing all DSN entries so far. If so, and you fix the other problem, the first time you have a non-DSN entry, you'll run into this problem unless it fix it as well.
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.
So here's my Code:
public double evaluate(){
Stack numbers = new Stack();
Stack operators = new Stack();
String[] divert = {};
String problem = "2 + 2 + 3";
divert = problem.split(" ");
for(int i = 0; i < divert.length; i++){
if(divert[i].equals("*") || divert[i].equals("/")|| divert[i].equals("+") || divert[i].equals("-")){
if(operators.peek().equals("*") || operators.peek().equals("/")){
int a = Integer.parseInt((String)numbers.pop());
int b = Integer.parseInt((String)numbers.pop());
String operand = (String)operators.pop();
numbers.push(doMath(b, operand, a));
}
else if ( divert[i].equals("+") || divert[i].equals("-")){
operators.push(divert[i]);
}
} else {
numbers.push(divert[i]);
}
}
while(!operators.empty()){
int a = Integer.parseInt((String)numbers.pop());
int b = Integer.parseInt((String)numbers.pop());
String operand = (String)operators.pop();
numbers.push(doMath(a, operand, b));
}
double endNumber = (double)numbers.pop();
return endNumber;
}
I keep getting weird errors, one telling me that the if(operators.peek().equals... bit in the nested if statement returns an EmptyStackException.
I get another error while trying to cast the popped number (endNumber) off to return it. I get an issue with casting that as a double.
If someone would look at this and tell me what is the problems and any possible way to resolve the issue, that would be great because I really don't understand why it's giving me these errors.
I know that removing the divert[i].equals("+")/("-") removes the issue for the first error, but that isn't very conductive to what I'm doing.
For the problem with doubles use the generics capability of Stack
Stack<Double> numbers = new Stack<Double>();
this will ensure only Doubles are stored on the stack. The auto unboxing (converts doubles to Doubles and visa-versa) feature means you should be able to do
double x = 5.0;
numbers.push(x);
double y = numbers.pop();
For good form also use
Stack<String> operator;
For testing the operator stack use
if( !operators.empty() && (operators.peek().equals("*") || operators.peek().equals("/")) )
i.e. test if the stacks is not empty before peeking.
Also check the order you popping numbers off the stack, in the code at the end. I've a feeling you will have problems with "5 - 3".
Also you always want to push the current operator. It looks like a "*" or "/" will never get pushed.
I apologize in advance, I am a java noob.
I have this in a statement
if(a==0 && b<4)
{
value = ((elev[a][b]-elev[a+1][b])*0.00001* double "variable" ) ;
}
So my main question is would the following....
(elev[a][b]-elev[a+1][b])
return an int value (assuming that the array was initialized and populated with int values, and that for a==0 and b<4 none of the references are null.
Sorry in advance if this is silly. Please don't feel inclined to comment, but help would be appreciated. I haven't done a lot of this java stuff.
When i populated the array, I printed it's contents to make sure I was populating correctly, and everything is where it should be...
Alas, I get a null pointer error wherever that (elev[a][b] - elev[a+1][b]) is first referenced....yet i know that the values are being put there.
Next question. When i populate an array, if i want to reference the values,
while(input.hasNextInt())
{
elev[i][j] = input.nextInt(); <-- this is how i was doing it
}
of elev[][]... do i need to say
elev[i][j] = new input.nextInt();
or is how i was doing it sufficient. When i populated an ArrayList from a file I had to use the "new" prefix So i was trying to figure out why i would get a null there.
Like i said I did print the array after reading it from the file and it printed out everything was in its place.
Thanks everyone.
EDIT
ok sorry for simplicity sake i didn't put in the actual code of "value"
it is actually
double randKg = getRandKg(avgKgNitrogen[z]);
double gradient = 0.00001
double under = ((randKg *(elev[a][b] - elev[a+1][b]) * gradient));
2nd Edit
This is the code for how i populated.
try{
File file = new File(filename);
Scanner input = new Scanner(file);
int rows = 30;
int columns = 10;
int elev[][] = new int[30][10];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j)
{
while(input.hasNextInt())
{
elev[i][j] = input.nextInt();
}
}
}
input.close();
}
catch (java.io.FileNotFoundException e) {
System.out.println("Error opening "+filename+", ending program");
System.exit(1);
}
3rd edit
So i am getting the null pointer here.....
(elev[a][b] - elev[a+1][b]) > 0 )
Which is why i originally asked. I have printed the array before when i populated and everything is where it should be.
You are getting a null pointer exception because double "variable" does not indicate to any integer or double value. Compiler is just trying to convert String 'variable' into double which is not possible. So, try eliminating the Double Quotes from "variable". Moreover you have not declared the data type of value variable.
Ignoring other problems in your code (covered by other answers), here's about your actual question:
If the code
if(a==0 && b<4) {
value = (elev[a][b] - elev[a+1][b]);
}
crashes with NullPointerException, it means elev is null. Assuming a and b are of type int, then there is no other way this can generate that exception (array out of bounds exception would be different). There are two options for the cause:
You execute above code before you do int elev[][] = new int[30][10];, so that elev still has the initial null value.
elev in the crashing line is a different variable than elev in initialization shown in the question.
And in you code, it seems to be 2. You create local elev in the initialization. It goes out of scope and is forgotten. You probably should have this initialization line in your method:
elev = new int[30][10];
And then you should have a class member variable instead of local variable in a method:
private int[][] elev;
class TwoDimArryAlloc {
public static void main(String[] args) {
int itemno[][] = new int[][] { {2234,2235,2236,2237,2238} , {3334,3335,3336,3337,3338} };
int it;
String itemdesc[][] = new String[][] {{"Womans Item1","Womans Item2","Womans Item3","Womans Item4","Womans Item5"},{"Mans Item1","Mans Item2","Mans Item3","Mans Item4","Mans Item5"}};
for (int i=0; i<2; i++)
{
for(int j=0; j<5; j++)
{
System.out.println(itemno[][]);
}
}
}
}
In the above program, I got the following error:
C:\Java Programs\TwoDimArryAlloc.java:18: '.class' expected
System.out.println(itemno[][]);
^
1 error
Process completed.
Can anyone help me solve this error?
You need to provide the array index:
System.out.println(itemno[i][j]);
^ ^
Instead of
System.out.println(itemno[][]);
you want to say
System.out.println(itemno[i][j]);
Without specifying which indexes you want, it is bad syntax, which confuses the compiler so much that it emits an impenetrable error message.
(The first pass of compilation is to construct a syntax tree, and this happens before the compiler figures out which names denote types and which ones denote variables. So when it sees itemno[][] it reasons that this could be the beginning of a valid expression if only itemno were the name of a type, but in that case the full expression would have to be itemno[][].class -- so that's what it asks for even though you meant something entirely different).
{
int itemno[][] = { {2234,2235,2236,2237,2238} , {3334,3335,3336,3337,3338} };
int it;
String itemdesc[][] = {{"Womans Item1","Womans Item2","Womans Item3","Womans Item4","Womans Item5"},{"Mans Item1","Mans Item2","Mans Item3","Mans Item4","Mans Item5"}};
for (int i=0; i<2; i++)
{
for(int j=0; j<5; j++)
{
System.out.println(""+itemno[i][j]);
}
}
}
You forgot to provide index in SYSO statement. Make it as follow:
System.out.println(itemno[i][j]);
You forgot to use the indexes:
System.out.println(itemno[i][j]);