Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have been trying using the Arraylist, but that dint seem to work
I need one simple example for index out of bound exception handling using the try catch blocks in java
This is my code, how do I integrate with try catch blocks to handle the exception?
import java.util.ArrayList;
public class NewClass2 {
public static void main(String[] args) {
ArrayList<String> lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
// in the next line, an IndexOutOfBoundsException occurs
System.out.println(lis.get(2));
}
}
Can I also get an example for Illegal Argument exception using the try catch
Don't try to use try/catch blocks to catch the exception. You can check if the index you are trying to pass is negative, or greater than or equal to the size, and avoid the exception ever being thrown in the first place.
As described in the Javadoc of ArrayList.get(int):
[Throws] IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
So, just check this in your code:
if (i >= 0 && i < lis.size()) {
// Do something for an index in bounds.
} else {
// Do something for an index out of bounds.
}
Only use exception handling for cases which you cannot avoid by checking in advance. This is covered in detail in Effective Java; in the 2nd Ed this is Item 57: "Use exceptions only for exceptional conditions".
Here is a basic example:
int[] num = {1, 3, 4, 5};
try {
System.out.println(num[30]);
}
catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace(System.out);
}
And for an ArrayList:
try {
ArrayList<String> lis = new ArrayList<String>();
lis.add("My");
lis.add("Name"); System.out.println(lis.get(2));
}
catch(IndexOutOfBoundsException e) {
e.printStackTrace(System.out);
}
As many people already stated, you are trying to access the third element (index = 2, indexes start at 0) of a data structure that has only 2 elements.
However, you could apply try-catch for this like the following, for example:
public static void main(String[] args) {
ArrayList<String> lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
// now you just try the access
try {
System.out.println(lis.get(2));
// and especially handle the IndexOutOfBoundsException
} catch (IndexOutOfBoundsException ex) {
System.err.println("You are trying to access an index that is not available (out of bounds)!");
ex.printStackTrace();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can anybody tell me what's wrong with my code
latest_songs,top_songs and hit_songs are arraylist.song() is a static method in Parseurl where i fetch the json array.it working fine & return proper data.
latest_Songs = ParseUrl.song(url1);
Log.i("ring,latest=", latest_Songs.toString());
top_Songs = ParseUrl.song(url2);
Log.i("ring,top=", top_Songs.toString());
hit_Songs = ParseUrl.song(url3);
Log.i("ring,hits=", hit_Songs.toString());
it works fine when i run latest_songs and top_songs.problem is with hit_songs.as i write this in my project both arraylist(latest_songs and top_songs) data overrided with hits_songs.where i am doing wrong.
this is ParseUrl from where i retrieve data in each arraylist
public class ParseUrl {
static ArrayList<String> songs_List = new ArrayList<String>();
static ArrayList<String> songs_Names = new ArrayList<String>();
static ArrayList<String> songs_Urls = new ArrayList<String>();
static File tempFiles;
File ringtones;
public static ArrayList<String> song(String url) {
songs_Names.clear();
songs_Urls.clear();
JSONObject json = JsonParse.getSongfromUrl(url);
try {
JSONArray latestSongs = json.getJSONArray("ringtones");
for (int count = 0; count < latestSongs.length(); count++) {
JSONObject song = latestSongs.getJSONObject(count);
songs_List.add(song.toString());
JSONArray name = song.names();
songs_Names.add(name.toString());
String songUrl = name.toString();
String URL = songUrl.substring(2, songUrl.lastIndexOf("\""));
songs_Urls.add(song.getString(URL));
}
} catch (JSONException e) {
e.printStackTrace();
}
return songs_Names;
}
Your arraylist is a static variable inside your class.So there is only one arraylist in memory.Each time you call the song method , you are modifying the same list.That means your latest_songs,top_songs,hit_songs, all will be pointing to same list.That is the reason your list is getting over ridden.
Try creating a list inside your method and return it rather than going for static variables.
Are you changing the url value anywhere?
Because you are assigning ParseUrl.song(url) to all the three array lists. Unless url is changed somewhere, all three array lists will have the same value since ParseUrl.song(url) will give the same result.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}
Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am working on some project in java.
Here I'm stuck at this problem and not able to figure out where I am going wrong.
I have made two classes: Test and Child.
When I run the code I am get a NullPointerException.
package com.test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}
Here's the problem:
String[] a = null;
a[0]="This";
You're immediately trying to dereference a, which is null, in order to set an element in it. You need to initialize the array:
String[] a = new String[4];
a[0]="This";
If you don't know how many elements your collection should have before you start populating it (and often even if you do) I would suggest using a List of some sort. For example:
List<String> a = new ArrayList<String>();
a.add("This");
a.add("is");
a.add("not");
a.add("working");
return a;
Note that you have another problem here:
int i=0;
while(i<b.length)
System.out.println(b[i]);
You're never changing i, so it will always be 0 - if you get into the while loop at all, you will never get out of it. You want something like this:
for (int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}
Or better:
for (String value : b)
{
System.out.println(value);
}
This is the problem:
String[] a = null;
a[0]="This";
They highlighted the problem of your probably the definition of null pointer exception would give you an idea what and where to find the problem in future. From java api doc, it defined what is npe and under what situation it will be thrown. Hope it help you.
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.
package test;
public class Test {
child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method()
{
String[] b;
b = newchild.main();
int i=0;
while(i<b.length){
System.out.println(b[i]);
i++;
}
}
}
package test;
public class child {
public String[] main() {
String[] a = {"This","is","not","Working"};
return a;
}