I'm having trouble passing a method with a parameter to another class.
In my main class I declare:
searchMap search = new searchMap();
search.search(null, 0);
In my other class, I have that as:
public boolean search(int[][] map, int fuel)
{
int totalSum = 0;
int row[] = new int[map.length];
boolean valid = true;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (i == j)
continue;
valid = valid && possiblePath(map, fuel, 0, i, j);
}
}
if(totalSum <= fuel)
{
System.out.println("This map is solvable :)");
return true;
}
else
{
System.out.println("This map is NOT solvable :(");
return false;
}
}
And I keep getting:
Exception in thread "main" java.lang.NullPointerException
at searchMap.search(searchMap.java:33)
at loadMap.load(loadMap.java:117)
at loadMap.main(loadMap.java:23)
I've tried everything and can't break from the NullPointerException. I've tried calling other ints, I've tried calling map[][], and I've had no success. Help would be greatly appreciated!!
EDIT:
public static void main(String[] args)
{
loadMap load = new loadMap();
load.load();
}
public void load()
{
JFileChooser chooser = new JFileChooser();
Scanner readLine = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
readLine = new Scanner(selectedFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int setMapSize = 0;
int i;
int j;
int toNode;
int edge;
setMapSize = readLine.nextInt();
readLine.nextLine();
int rowCounter = 0;
int[][] map = new int[setMapSize][setMapSize];
int[] row = new int[setMapSize];
int sum = 0;
int totalSum = 0;
System.out.println("MAP: " + map.length);
do
{
String line = readLine.nextLine();
Scanner newLine = new Scanner(line);
do
{
toNode = newLine.nextInt();
edge = newLine.nextInt();
map[rowCounter][toNode] = edge;
} while(newLine.hasNextInt());
rowCounter++;
newLine.close();
} while (rowCounter < setMapSize);
int fuel = readLine.nextInt();
System.out.println("Fuel: " + fuel);
readLine.close();
}
searchMap search = new searchMap();
search.search(null, 0);
}
You are passing in a null map, then turning around and calling this line.. map will be null and you are unable to call .length on a null.
int row[] = new int[map.length];
You could fix this by adding a check to make sure the parameter map is not null
public boolean search(int[][] map, int fuel) {
boolean valid = false;
if (map != null) {
int totalSum = 0;
int row[] = new int[map.length];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map.length; j++) {
if (i == j) continue;
valid = valid && possiblePath(map, fuel, 0, i, j);
}
}
if (totalSum <= fuel) {
System.out.println("This map is solvable :)");
return true;
} else {
System.out.println("This map is NOT solvable :(");
return false;
}
}
return valid;
}
it is because you put null in for the map.
null is normally fine as a placeholder but when you do things like:
map.length
you are asking for a property of a null value.
null values have no properties.
try putting a test map in instead.
A null pointer exception occurs probably means that you are trying to access something which doesn't exist.
In this case, your int[][] map is null and in the 2nd line of you search method, you are trying to get the map.length. Make any sense to you? Java is unable to get the length of an array which does not exist, thus giving your the nullPointerException.
You can solve your problem by either:
Pass in an array reference instead of null when calling your method.
Do this in your main:
searchMap search = new searchMap();
int[][] map = new int [5][5]; //Just an example
search.search(map, 0); //Pass in an existing 2D array instead of null
OR
Add a check to see whether array is null
You can do it as below:
if (map== null)
length = 0;
else
length = map.length;
int row[] = new int[length];
Personally, as a habit, I will also suggest your refrain from using similar names for methods and objects.
You're calling:
search.search(null, 0);
so you pass null as the map parameter..
Which will cause NullPointerException starting here since a null does not have a length property:
int row[] = new int[map.length];
You need to pass in your map instead of passing a null value. Providing your SearchMap class would probably help.
Now that I see you're declaring map:
int[][] map = new int[setMapSize][setMapSize];
Then when you want to pass in the map to the search function, you should call
search.search(map, 0);
int[][] is the type of the variable map, so there is no need to use [][] when using the variable.
You also declared map inside the if so it's out of scope by the time you call it for search.
I think you want to move it inside that if statement since you don't want to search when there's no file.
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
// ...
int[][] map = new int[setMapSize][setMapSize];
// ...
searchMap search = new searchMap();
search.search(map, 0);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I need to create an array list using generics. My add method seems to work sometimes, however my get method appears to have a good amount of problems and i don't receive a compile error. However when i try to get an object from the Array list using my get method it throws a java out of bounds exception. here i what i have so far, and i am using BlueJ. Also, the instructions were to set the initial "illusion" length to zero.
public class AL <X> {
private X[]data;
private int count;
public AL() {
count = 0;
data = (X[]) new Object[0];
}
public void add (X v) {
if (data.length != count) {
data[count] = v;
count++;
} else {
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length; i++) {
newdata[i] = data [i];
}
count++;
data = newdata;
}
}
public X get(int index) {
if (index >= count || index < 0) {
throw new ICantEven();
} else {
return data[index];
}
}
}
Your add method doesn't work, since the initial backing array you are using has a 0 length, which remains 0 even when you try to double it (since 0*2==0).
You also forgot to actually add the new element when you resize the backing array. If you hadn't forgot that, you'd get the exception in add.
First of all, change the initial size of the array created by your constructor to be positive :
data = (X[]) new Object[10];
Then add
data[count] = v;
to the else clause of your add method (just before count++;).
Your add method can be further simplified :
public AL()
{
count = 0;
data = (X[]) new Object[10];
}
public void add (X v)
{
// resize backing array if necessary
if (data.length == count)
{
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length;i++ )
{
newdata[i] = data [i];
}
data = newdata;
}
// add new element
data[count] = v;
count++;
}
I am relatively new to java, and this is only the second time I have ever tried to design a program that has an array of class objects. I am having trouble because when I go into debug mode, it is showing me that the arrays are being built correctly. However, when I try to build a string or even print to the console, I am getting a null pointer exception.
I am trying to make an array of Slot class objects.
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
Slot[] s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
And the Slot class has its own array, block[], constructed by a value passed in through its constructor.
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
short block[] = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Later in the program I then try to print to the console or build a string and it always breaks when I try to use any element in the slot[] in the C class.
Have I instantiated and initialized my 2 different arrays correctly?
public class C {
int slotNum;
Slot[] s;
public C(int byteSize, int slotNum){
this.slotNum = slotNum;
s = new Slot[slotNum]; //create an array of slots
for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
s[i] = new Slot(byteSize);
}
display();
}
Try something like these instead
public class Slot {
boolean v;
short block[];
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
Replace
short block[] = new short[byteSize];
with
block = new short[byteSize];
Always use a this operator to initialize in a constructor so that you may differentiate clearly between local variables and instance variables
public Slot(int byteSize){
valid = false;
//Instantiate each element in block[] to 0
this.block = new short[byteSize];
for(int i = 0; i < block.length; i++){
block[i] = 0;
}
}
I'm trying to make a game for my Java class, but I keep getting a NPE. I know that it means one of the variables being passed is a null, but I have no idea where. I have checked all variables involved. I believe it may be an issue with initializing the arrays, but I'm still not seeing what I've done wrong. I've checked around stack overflow and I have seen NPEs due to various reasons, but I can't find a solution that works on mine.
public class Inventory{
public int gold = 0;
private Item[] itemListArray = new Item[30];
private JButton[] itemButtonArray = new JButton[30];
private JButton buttonBack = new JButton("Back");
private static final String HOME = "Home";
public Inventory() {
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
}}
That is where the NPE calls for the error
public class Item {
protected String name = "";
protected int def = 0;
protected int stack = 100;
protected boolean stackable = false;
protected boolean consume = false;
boolean emptySlot = true;
protected ImageIcon icon;
public Item(){
}
public boolean isArmor()
{
if(def >= 1)
{
return true;
} else {
return false;
}
}
public boolean isConsumable()
{
if(consume = true)
{
return true;
} else {
return false;
}
}
public boolean isEmpty()
{
if(emptySlot = true)
{
return true;
} else {
return false;
}
}
Here is the declaration of Item.
Please Answer soon to my issue, I can't seem to figure it out.
Item[] itemListArray = new Item[30];
This code just creates an array that contains null values, you need to initializes each individual value in the array.
for(int i = 1;i < 31; i++)
{
itemListArray[i].emptySlot = true; //Here is where the NPE hits
}
And this cycle will cause ArrayIndexOutOfBoundsException later because in Java valid array indexes start from 0 and go to array.length-1 (0 to 29 in your case), while this code will try to access itemListArray[ 30 ].
It isn't sufficient for you to instantiate your array, you must also populate it with objects. Otherwise each index contains null by default.
private Item[] itemListArray = new Item[30];
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}
You instantiate your array with private Item[] itemListArray = new Item[30]; which creates an array of type Item with 30 null entries.
When you call itemListArray[i].emptySlot in your loop in the constructor you are accessing a variable from a null object.
You will have to instantiate any Item objects in your array in the loop in your constructor (or elsewhere) before you can access any variables or invoke any methods from them.
Also your for loop is skipping the first element. The first element in Java has an index of 0.
I guess you may haven't understand initialization in java.you just initialize a array ,but it haven't refer to the real object.
code like this will help:
for(int i = 1;i < 31; i++){
Item item = new Item();
item.emptySlot = true;
itemListArray[i] = item; //Here is where the NPE hits
}
try to use a constructor in Item class is much better,hope it work.
Creating an array of objects defaults all of them to null. You need to put an object into each element of the array to get rid of this problem.
for (int i = 0; i < itemListArray.length; i++) {
itemListArray[i] = new Item();
}
for (int j = 0; j < itemButtonArray.length; j++) {
itemButtonArray[j] = new JButton();
}
I wanted to know if there's a native method in array for Java to get the index of the table for a given value ?
Let's say my table contains these strings :
public static final String[] TYPES = {
"Sedan",
"Compact",
"Roadster",
"Minivan",
"SUV",
"Convertible",
"Cargo",
"Others"
};
Let's say the user has to enter the type of car and that then in the background the program takes that string and get's it's position in the array.
So if the person enters : Sedan
It should take the position 0 and store's it in the object of Cars created by my program ...
Type in:
Arrays.asList(TYPES).indexOf("Sedan");
String carName = // insert code here
int index = -1;
for (int i=0;i<TYPES.length;i++) {
if (TYPES[i].equals(carName)) {
index = i;
break;
}
}
After this index is the array index of your car, or -1 if it doesn't exist.
for (int i = 0; i < Types.length; i++) {
if(TYPES[i].equals(userString)){
return i;
}
}
return -1;//not found
You can do this too:
return Arrays.asList(Types).indexOf(userSTring);
I had an array of all English words. My array has unique items. But using…
Arrays.asList(TYPES).indexOf(myString);
…always gave me indexOutOfBoundException.
So, I tried:
Arrays.asList(TYPES).lastIndexOf(myString);
And, it worked. If your arrays don't have same item twice, you can use:
Arrays.asList(TYPES).lastIndexOf(myString);
try this instead
org.apache.commons.lang.ArrayUtils.indexOf(array, value);
Use Arrays class to do this
Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");
No built-in method. But you can implement one easily:
public static int getIndexOf(String[] strings, String item) {
for (int i = 0; i < strings.length; i++) {
if (item.equals(strings[i])) return i;
}
return -1;
}
There is no native indexof method in java arrays.You will need to write your own method for this.
An easy way would be to iterate over the items in the array in a loop.
for (var i = 0; i < arrayLength; i++) {
// (string) Compare the given string with myArray[i]
// if it matches store/save i and exit the loop.
}
There would definitely be better ways but for small number of items this should be blazing fast. Btw this is javascript but same method should work in almost every programming language.
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
Testable mockable interafce
public interface IArrayUtility<T> {
int find(T[] list, T item);
}
implementation
public class ArrayUtility<T> implements IArrayUtility<T> {
#Override
public int find(T[] array, T search) {
if(array == null || array.length == 0 || search == null) {
return -1;
}
int position = 0;
for(T item : array) {
if(item.equals(search)) {
return position;
} else {
++position;
}
}
return -1;
}
}
Test
#Test
public void testArrayUtilityFindForExistentItemReturnsPosition() {
// Arrange
String search = "bus";
String[] array = {"car", search, "motorbike"};
// Act
int position = arrayUtility.find(array, search);
// Assert
Assert.assertEquals(position, 1);
}
Use this as a method with x being any number initially.
The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")
I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.
What is the best way to accomplish this?
public static boolean duplicates (int [] x)
I am prompting for user data like so:
public static void readData (int [] x, int i){
Scanner input = new Scanner(System.in);
System.out.println("Please enter integers, enter -999 to stop");
while (i <= 99) {
int temp = input.nextInt();
if(temp == -999){
break;
}
else {
x[i++]=temp;
}
// else
}//end while
printArray(x,i);
}//end readData
public static void printArray(int [] x, int numElementsInX){
int n = numElementsInX;
for (int i = 0; i < n; i++){
System.out.print(x[i] + " ");
}//end for
System.out.println();
}//end printArray
I am sure there is a better way to do this, but this is how I have been taught so far.
Here is a solution that:
Compiles and executes without throwing.
Uses numElementsInX as you requested.
Returns as soon as it finds a duplicate.
This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.
public static boolean duplicates (int [] x, int numElementsInX ) {
Set<Integer> set = new HashSet<Integer>();
for ( int i = 0; i < numElementsInX; ++i ) {
if ( set.contains( x[i])) {
return true;
}
else {
set.add(x[i]);
}
}
return false;
}
Here's a sample program containing the above code.
this should do it.
public boolean containsDuplicates(Integer[] x) {
return new HashSet<Integer>(Arrays.asList(x)).size() != x.length
}
You dont need numElementsInX as this is the same as x.length
edit after comment from Louis. Arrays.asList does not work with int arrays.
To convert int[] to Integer try this question How to convert int[] to Integer[] in Java?
or do soemthing like this (not tested but from memory)
Integer[] newArray = new Integer[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
This certainly isn't the most efficient way, but since you don't know about Sets yet, you can use two loops:
public static boolean duplicates (int [] x){
for (int i=0; i<numElementsInX; i++){
for (int j=i+1; j<numElementsInX; j++){
if (x[j]==x[i]) return true;
}
}
return false;
}
"set.add()" returns true if the element is not already present in the set and false otherwise. We could make use of that and get rid of "set.contains()" as in the above solution.
public static boolean duplicates (int[] x, int numElementsInX) {
Set<Integer> myset = new HashSet<>();
for (int i = 0; i < numElementsInX; i++) {
if (!myset.add(x[i])) {
return true;
}
}
return false;
}
For java, return true if the array contains a duplicate value,
boolean containsDuplicates(int[] a) {
HashSet<Integer> hs = new HashSet<>();
for(int i = 0; i<a.length; i++) {
if(!hs.add(a[i])){
return true;
}
}
return false;
}