Reputation: 11
I got this error message when trying to run a school project. If it's helpful I need to write a code that takes in strings from the user and counts the amount of #'s they enter.
Here is my project code:
package edu.bsu.cs121.albeaver;
import java.util.*;
public class HashTagCounter {
public static void main(String args[]){
boolean go = true;
System.out.println("Please tweet your tweets: ");
Scanner twitterInput = new Scanner(System.in);
String tweet = twitterInput.next();
ArrayList<String> tweets = new ArrayList<String>();
while(go == true){
tweets.add(tweet);
if(tweet == "done"){
go = false;
}
}
System.out.println(tweets);
twitterInput.close();
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at edu.bsu.cs121.albeaver.HashTagCounter.main(HashTagCounter.java:16)
I'm not sure what to do...
Upvotes: 0
Views: 142
Reputation: 4843
There are several items you should take from this learning experience:
String1.equalsIgnoreCase(String2)
(If case matters, then one uses String1.equals(String2).)For loops that involve getting input from somewhere you may want to use the form
line = [get input]
while (!line.equealsIgnoreCase([end string]) {
[ do work on line ]
line = [get input]
}
Upvotes: 0
Reputation: 328568
You are looping forever (even after correcting the ==
error) because you always check the same tweet. This would probably work better:
List<String> tweets = new ArrayList<String>();
while (true) {
String tweet = twitterInput.next();
if ("done".equals(tweet)) break;
tweets.add(tweet);
}
Upvotes: 4
Reputation: 2826
The problem is, that you first read the tweet and then initiate a while cycle, that adds the same tweet over and over again, until you run out of memory. Add
System.out.println(tweets.size());
behind
tweets.add(tweet);
to get a better grasp of what's happening.
Upvotes: 1
Reputation: 1479
while(go == true){
tweets.add(tweet);
if(tweet.equals("done")) { // this line should be changed
go = false;
}
}
In your case, tweet == "done"
is never going to execute, and hence the while loop gets to infinite loop. This causes Null Pointer Exception
.
Upvotes: 1
Reputation: 8815
You are never setting go
to true
because the String
comparison never succeeds. Don't compare strings with ==
. Use the equals()
method instead. So change:
if(tweet == "done"){
to:
if(tweet.equals("done")){
However, this won't solve your problem entirely. You also need to update the tweet
variable inside of the loop, otherwise you'll always be comparing against the same String
. See assylias' answer for a code example.
Upvotes: 1