Nullpointerexception when I perform depth first search [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}

I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number

Related

HashMap - Adding a value to a specific item [duplicate]

This question already has answers here:
How to update a value, given a key in a hashmap?
(17 answers)
Closed 11 months ago.
public void addItem(String itemName,int numItemAdd) {
HashMap <String,Integer> items = new HashMap<String,Integer>();
int totalval;
totalval =+ numItemAdd;
items.put(itemName,totalval);
}
I am new to HashMaps. I am wanting to add the integers to the specific itemName. For example, addItem("socks",100); addItem("socks",200). Whenever I do this, instead of getting 300 I only get 200. I know that put() replaces the last value used, but I do not know how to add the numbers so that I can get 300 instead of having the last value used.
You can try this, it also manages the case when socks don't exist:
private HashMap <String,Integer> items = new HashMap<String,Integer>();
public static void main(String[] args) {
Test test = new Test();
test.addItem("socks", 100);
test.addItem("socks", 200);
}
public void addItem(String itemName,int numItemAdd) {
items.put(itemName,items.get(itemName) != null ? (items.get(itemName) + numItemAdd) : numItemAdd);
System.out.println("Socks value:" + items.get(itemName));
}

Why does my list not change with lambda? [duplicate]

This question already has answers here:
Remove objects from an ArrayList based on a given criteria
(10 answers)
Closed 5 years ago.
I have the following simple method:
public void exercise2(List<String> list) {
list.stream().filter(s -> s.length() % 2 == 0).collect(Collectors.toList());
}
And simple test, which does not complete successfully:
#Test
public void testExercise2() {
Lesson1 lesson1 = new Lesson1();
List<String> list = new ArrayList<>(Arrays.asList("alpha", "bravo", "charlie",
"delta", "echo", "foxtrot"));
List<String> inputList = new ArrayList<>(list);
lesson1.exercise2(list);
assertEquals("Input " + inputList.toString(), Arrays.asList("echo"), list);
}
Streams never modify the original list.
Your function creates a new list, then ignores it.

Dictionary of Words: need to scan each element for word length and make searchable [duplicate]

This question already has answers here:
length of each element in an array Java
(4 answers)
Closed 5 years ago.
I have converted a file of words into a String array. I need to somehow convert the Array into a list of word lengths and make it searchable. In other words, I need to be able to enter a word length (say, 5) and be presented with only the words that have a word length of five. Help?
public static void main(String[] args) throws IOException {
String token1 = "";
Scanner scan = new Scanner(new File("No.txt"));
List<String> temps = new ArrayList<String>();
while (scan.hasNext()){
token1 = scan.next();
temps.add(token1);
}
scan.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
You don't use an array for that. The things you need are collections, more precisely: Maps and Lists; as you want to use a Map<Integer, List<String>>.
Meaning: a map that uses "word length" as key; and the mapped entry is a list containing all those words with that length. Here is a bit of code to get you started:
Map<Integer, List<String>> wordsByLength = new HashMap<>();
// now you have to fill that map; lets assume tempsArray contains all your words
for (String s : tempsArray) {
List<String> listForCurrentLength = wordsByLength.get(s.length());
if (listForCurrentLength == null) {
listForCurrentLength = new ArrayList<>();
}
listForCurrentLength.add(s);
wordsByLength.put(s.length(), listForCurrentLength);
The idea is basically to iterate that array you already got; and for each string in there ... put it into that map; depending on its length.
( the above was just written down; neither compiled nor tested; as said it is meant as "pseudo code" to get you going )

Getting Null pointer exception when trying to add two string elements [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I was asked following question in an interview :
Array a = {1,2,3,4,5}, Array b = {a,b,c,d,e}, write a program to add individual elements of both array and enter the sum in third array with output like {e1, d2, c3, b4, a5}
I was not able to come up with solution at that time and now I am trying at home and wrote following code but got null pointer exception :
public class ArrayMergeIndividualElements {
String[] a = {"1","2","3","4","5"};
String b[] = {"a","b","c","d","e"};
String s[]=null;
void mergeArrays()
{
int k=0;
int j=b.length-1;
for(int i=0;i<a.length;i++)
{
for(;j>=0;)
{
System.out.println("Number array is "+a[i]);
System.out.println("String array is "+b[j]);
s[k]=a[i]+b[j]; //getting null pointer exception at this line
k++;
j--;
break;
}
}
System.out.println("output is :");
for(int l=0;l<s.length;l++)
{
System.out.print(s[l]);
}
}
public static void main(String[] args) {
ArrayMergeIndividualElements amie = new ArrayMergeIndividualElements();
amie.mergeArrays();
}
}
I have tried following code by searching on stackoverflow , but no luck
String[] both = Stream.concat(Arrays.stream(a[i]), Arrays.stream(b[j]))
.toArray(String[]::new);
Individually arrays are printing the value but when I try to add/concatenate them I am getting null pointer.
Also can we add both arrays if one is Integer array and other is String array?
Please help
You simply have to initialize your destination array with :
String[] s = new String[a.length];
If you didn't do that, when you try to add something to that array you obtain a NullPointerException.
You have not initialized your array. Try doing
String s[]= new String[a.length];

Add String Values from a for loop to list [duplicate]

This question already has answers here:
How to make a new List in Java
(25 answers)
Closed 7 years ago.
public static void printFiles(NodeList node) {
for (int i = 0; i < node.getLength(); i++) {
Node file = node.item(i);
String nodeValue = file.getAttributes().getNamedItem("urlName").getNodeValue();
System.out.println(nodeValue);
}
}
output:
0a4f171c-e0a4-4aa8-b43b-3989c235ff58.txt
0ccfa1a4-16b0-4e1f-abc9-e17907bb591f.txt
17c0545b-377e-4e0a-bb45-29f38fc91533.txt
3b341bf0-2cd7-46fe-a834-5b67804e5ff1.txt
48121209-d58e-4565-83b7-05062799be6e.txt
511b7a89-e4de-4f6e-9c8f-5ba65f675d7b.txt
compress.txt
dadadada.txt
e0c44cb9-2b1c-444c-a429-64531ea6a9a0.txt
e68b1d1d-9a66-4678-a6c1-76c64ae8be08.txt
hgafgahfka.txt
jdjajhdajdajd.txt
test1.txt
test2.txt
I parsed the xml document and got the values through for loop but those alues need to be in single place like List so that I can pass to some other function.can some one please let me know how to add those in a List .Below is the code and the current Output.
String input = "hello world";
List<String> list = new ArrayList<>();
list.add(input);
System.out.println(list.get(0));
> hello world
Good luck

Categories