Exceptions being thrown with getting a status with twitter4j? - java

I was trying to follow the docs here: https://github.com/yusuke/twitter4j/blob/master/twitter4j-examples/src/main/java/twitter4j/examples/tweets/ShowStatus.java but appear to have gone wrong somewhere. I'm trying to do something slightly different then the docs however. I am not taking args, and am using a hardcoded username instead. Here is the code that is troubling.
import twitter4j.Twitter;
import twitter4j.Status;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
public class ChrisTwitter {
public Status status;
public ChrisTwitter (){
Twitter twitter = new TwitterFactory().getInstance();
try {
Status status = twitter.showStatus(Long.parseLong("rye761"));
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
catch (TwitterException e) {
e.printStackTrace();
}
}
}
any ideas? Oh and here is what I get in the console: (new stack trace)
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
TwitterFactory.getInstance cannot be resolved to a type
The method Page(int, int) is undefined for the type ChrisTwitter
at com.github.ryebread761.lockergnome.ChrisTwitter.<init>(ChrisTwitter.java:16)
at com.github.ryebread761.lockergnome.Base$CTListener.actionPerformed(Base.java:121)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6140)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4737)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127)
at java.awt.Window.dispatchEventImpl(Window.java:2482)
at java.awt.Component.dispatchEvent(Component.java:4565)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:643)
at java.awt.EventQueue$1.run(EventQueue.java:641)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:657)
at java.awt.EventQueue$2.run(EventQueue.java:655)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:654)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

You're trying to parse an alphanumeric string to long and that's throwing the NumberFormatException:
Status status = twitter.showStatus(Long.parseLong("rye761"));
Since you're not catching a NumberFormatException in your try-catch block the exception propagates. To prevent this you should validate the input you try to parse before doing so or adding an aditional catch for that NumberFormatException.
EDIT
To get the latest tweet of an user, you can take this approach:
First of all define the paging of your request. In this case just ask for one page and one tweet per page (If I'm not mistaken it will be the latest one). Then you issue the request directly, since you're consulting a tweet and you're not doing anything else you don't need to authenticate AFAIK.
Twitter latestTweetChecker = new TwitterFactory.getInstance();
Paging page = Page(1,1);
List<Status> statusList = latestTweetChecker.getUserTimeline("rye761",page);
There, you'll have the status you need. Just grab the information you need with the corresponding methods.

Long.parseLong("rye761")
Even though input for parseLong is of format String, characters in the String must be all decimal digits, which is not case with rye761. So, you are getting exception
The characters in the string must all be decimal digits, except that
the first character may be an ASCII minus sign '-' (\u002D') to
indicate a negative value.

Related

In Java - how do I get a full stack trace

Currently I get the following output from code run
Caused by: java.lang.NullPointerException
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:227)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:256)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:560)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:514)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1192)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1132)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:219)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:312)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3189)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2114)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:937)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:443)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:394)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.parse(HtmlUnitNekoDOMBuilder.java:760)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:158)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:112)
at com.gargoylesoftware.htmlunit.javascript.host.Element.parseHtmlSnippet(Element.java:868)
at com.gargoylesoftware.htmlunit.javascript.host.Element.setInnerHTML(Element.java:920)
at com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.setInnerHTML(HTMLElement.java:676)
at sun.reflect.GeneratedMethodAccessor17.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:188)
... 30 more
The above ... 30 more means that I do not know the line of my code that causes the problem. How can I get the full stack trace.
Also, if it does not seem to be running any of my catch statements with printStackTrace, but if I turn off logging with the below command
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
**Have put in my full code below as suggested by the comments below . Did not put in the actual URL though**
import com.gargoylesoftware.htmlunit.html.*;
import java.io.File;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class download_to_send_to_stackoverflow
{
public static void main(String args[])
{
String url = "did not want to include the actual web site ";
HtmlPage page = null;
WebClient webClient = new WebClient();
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true); // tried making false - but didnt work
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setTimeout(30000);
webClient.setJavaScriptTimeout(30000); //e.g. 50s
webClient.waitForBackgroundJavaScript(15000) ; // added 2017/1/24
webClient.waitForBackgroundJavaScriptStartingBefore(30000) ; // added 2017/1/24
try
{
page = webClient.getPage( url );
savePage_just_html(page );
}
catch( Exception e )
{
System.out.println( "Exception thrown:----------------------------------------" + e.getMessage() );
e.printStackTrace();
}
}
protected static String savePage_just_html(HtmlPage page)
{
try
{
File saveFolder = new File("spool/_");
page.save(saveFolder); // this is the line causing the error with limit stack trace
}
catch ( Exception e )
{
System.out.println( "IOException was thrown: ---------------------------------- " + e.getMessage() );
e.printStackTrace();
}
return "file.html";
}
}
------------------------------------------------------
page.save(saveFolder); above is the problem line. if I take it out I dont get the limited statcktrace errors but I also dont save the html page - which I want to do
- The question is - why does this line only print a limited stacktrace
The "Caused by" means that this is a nested exception.
The "... 30 more" in a nested exception stacktrace means that those 30 lines are the same as in the primary exception.
So just look at the primary stacktrace to see those stack frames.
Apparently your exception stacktraces are being generated in a way that is suppressing (or removing) the primary exception stacktrace. This is puzzling, but it is probably being done by one of the unit testing libraries that you are using.
Getting to the bottom of this will probably involve you either debugging whatever it is that is generating the stacktrace, or writing a minimal reproducible example so that someone else can debug it.

PatternSyntaxException when trying to access Website with HtmlUnit

I'm currently trying to acces a Webpage in Javacode using HtmlUnit. The Page has a Button, which opens a new Page when clicked. But when I try to click it, the compiler throws this exception which can be found in the attached image. As far as I understand, it has something to do with illegal escape sequences in the page's Html code.
Here is my code so far:
try(WebClient client = new WebClient(BrowserVersion.CHROME)){
client.getOptions().setCssEnabled(false);
WebRequest webRequest = new WebRequest(url);
webRequest.setCharset("utf-8");
HtmlPage entrypage = client.getPage(webRequest);
HtmlInput dwnld = (HtmlInput) entrypage.getElementById("btn_download");
long millis = System.currentTimeMillis();
while (System.currentTimeMillis() <= millis+11000) {
//Do nothing, just wait 11 seconds
}
if (dwnld != null) {
System.out.println("Found btn_download");
dwnld.click();
}
} catch (FailingHttpStatusCodeException | IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ideas anyone?
Here's the exception:
java.util.regex.PatternSyntaxException: Illegal octal escape sequence near index 2
\0+$
^
at java.util.regex.Pattern.error(Pattern.java:1955)
at java.util.regex.Pattern.o(Pattern.java:3192)
at java.util.regex.Pattern.escape(Pattern.java:2300)
at java.util.regex.Pattern.atom(Pattern.java:2198)
at java.util.regex.Pattern.sequence(Pattern.java:2079)
at java.util.regex.Pattern.expr(Pattern.java:1996)
at java.util.regex.Pattern.compile(Pattern.java:1696)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1054)
at com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.doAction(HtmlUnitRegExpProxy.java:102)
at com.gargoylesoftware.htmlunit.javascript.regexp.HtmlUnitRegExpProxy.action(HtmlUnitRegExpProxy.java:74)
at net.sourceforge.htmlunit.corejs.javascript.NativeString.execIdCall(NativeString.java:455)
at net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject.call(IdFunctionObject.java:89)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpretLoop(Interpreter.java:1531)
at net.sourceforge.htmlunit.corejs.javascript.Interpreter.interpret(Interpreter.java:798)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.call(InterpretedFunction.java:105)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.doTopCall(ContextFactory.java:411)
at com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory.doTopCall(HtmlUnitContextFactory.java:309)
at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3057)
at net.sourceforge.htmlunit.corejs.javascript.InterpretedFunction.exec(InterpretedFunction.java:115)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$3.doRun(JavaScriptEngine.java:724)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:832)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:620)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:733)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:708)
at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptIfPossible(HtmlPage.java:982)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeInlineScriptIfNeeded(HtmlScript.java:351)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:411)
at com.gargoylesoftware.htmlunit.html.HtmlScript$3.execute(HtmlScript.java:276)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:290)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:793)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:751)
at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1170)
at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1072)
at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:206)
at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:330)
at org.cyberneko.html.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3126)
at org.cyberneko.html.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2093)
at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:920)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:499)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:452)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:1017)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:248)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:194)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:268)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:156)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:471)
at com.gargoylesoftware.htmlunit.WebClient.loadDownloadedResponses(WebClient.java:2110)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.doProcessPostponedActions(JavaScriptEngine.java:875)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.processPostponedActions(JavaScriptEngine.java:962)
at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1327)
at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1270)
at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1218)
at src.Hosts$1.exctractFileLinkFrom(Hosts.java:44)
at src.TestMain.main(TestMain.java:10)
Possible solution?!
It is possible that the Error here does not lie in the frameworks Htmlparsing. My sugggestion is, that not the HtmlUnit framework itself is unable to parse illegal escape sequences but it's logger might be.
I didn't intended to solve the problem this way, but when I changed the loggers level to SEVERE to clean up my console output, there is no such exception being thrown.
Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.SEVERE);
Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.SEVERE);
Is my suggestion here correct or is this just coincidence?

Java jList NullPointerException error

Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at test.factory.MainWindow.setFuncList(MainWindow.java:160)
at test.factory.MainWindow.<init>(MainWindow.java:22)
at test.factory.MainWindow$2.run(MainWindow.java:151)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Code:
TestFactory tf = new TestFactory();
ArrayList<Function> fList = tf.getFunctions();
DefaultListModel<Function> dFuncList = new DefaultListModel();
fListPane.setModel(dFuncList);
for(Function f : fList) {
dFuncList.addElement(f);
}
Question:
Now, if you find the error that's great, but my question is. How do I parse the error text to find where my error originated? I'm used to things like missing ';' at line 24 of C:\filename
Update: fList has two elements, so not null.
The error dump is a stack trace, so I tend to find it's always best to start at the top and work down. In this case it looks like your setFuncList at line 160 of MainWindow.java is trying to work with an object that is null (maybe not yet initialised?).
UPDATE: Example of code that works
class Function {
int i;
public Function(int myI) {
this.i = myI;
}
#Override
public String toString() {
return "i=" + this.i;
}
}
Used with:
ArrayList<Function> fList = new ArrayList<>();
fList.add(new Function(1));
fList.add(new Function(2));
DefaultListModel<Function> dFuncList = new DefaultListModel();
jList2.setModel(dFuncList);
for(Function f : fList) {
dFuncList.addElement(f);
}
So basically look through the stack trace from the top, it will list the calls that have occurred which led to the error you received. Look carefully at the lines in your code that are listed. If you can't see any obvious errors you can add some extra tests based on the error. Ie check some objects are not null before the line which caused the error, I find printouts a simple approach. You can also use a debugger, I use jswat but only break it out when I really need to.
Hope that was what you were after
#orangegoat gave a good breakdown of how to interpret the stack trace if that's what you wanted
Also a link to jswat
http://code.google.com/p/jswat/

Cannot initialise class within ActionListener... please help!

I have a Breadth-First algorithm that scans a graph of nodes.
I am new to UI and Swing. I want the algorithm to run when the OK button is pushed etc. using the text box strings as parameters.
The program will not work becuase it cannot initialise my class.
This code works perfectly in console. I just don't understand UI.
I should add that start.getText() and end.getText() are text boxes where the user enters the start and end stations.
JButton okButton = new JButton("Get Route...");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final BreadthFirstShortestPath init = new BreadthFirstShortestPath("/Users/wakemana/Documents/GC02 Java/Tube Stations List/station_names.txt"
, "/Users/wakemana/Documents/GC02 Java/Tube Stations List/tube_edges.txt");
init.breadthFirst(start.getText(), end.getText());
ArrayList<String> path = init.getPath();
for (String station : path) {
System.out.println(station);
}
}
});
buttonPane.add(okButton);
And for anyone that can help, here is the stack trace:
/Users/wakemana/Documents/GC02 Java/Tube Stations List/station_names.txt
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.File.<init>(File.java:222)
at alex.graph.breadthfirst.StationGraph.<init>(StationGraph.java:19)
at alex.graph.breadthfirst.BreadthFirstShortestPath.<init>(BreadthFirstShortestPath.java:22)
at alex.graph.breadthfirst.Main$1.actionPerformed(Main.java:103)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6352)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6117)
at java.awt.Container.processEvent(Container.java:2085)
at java.awt.Component.dispatchEventImpl(Component.java:4714)
at java.awt.Container.dispatchEventImpl(Container.java:2143)
at java.awt.Component.dispatchEvent(Component.java:4544)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
at java.awt.Container.dispatchEventImpl(Container.java:2129)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4544)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:635)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
The issue is NOT with the ActionListener. Your object BreadthFirstShortestPath is not being constructed properly. This is the relevant part of the stacktrace:
/Users/wakemana/Documents/GC02 Java/Tube Stations List/station_names.txt
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.File.<init>(File.java:222)
at alex.graph.breadthfirst.StationGraph.<init>(StationGraph.java:19)
at alex.graph.breadthfirst.BreadthFirstShortestPath.<init>(BreadthFirstShortestPath.java:22)
at alex.graph.breadthfirst.Main$1.actionPerformed(Main.java:103)
I think you are wrong and that the path is not being found. Your command line variables could differ from an IDE environment.
#Alex W : Try using : System.getProperty("user.dir") to get the current directory of the context , then use " ../ " to get the relative path for the location.I think that your using absolute path here is causing nullpointer exception as it could not find that location.

Java: printf stack error

I was trying to convert from println to printf and this is what I got.
//*********************************Output File*********************************
//Create a file with the information entered
//and the information processed
public void outputFile() throws IOException{
String payFileOutput=null;
PrintWriter file= new PrintWriter("DataOutput.txt");
file.printf("Your total expenses per month are %10f\n",
format.format(getTotalCost()));
file.printf("Your college tuition is %10f\n", format.format(getTuition()));
file.printf("Your rent is %10f\n", format.format(getRent()));
if(pay==1)
payFileOutput="Savings";
else if(pay==2)
payFileOutput="Loans";
else if(pay==3)
payFileOutput="Freelance Work";
else
;
file.printf("Your payment method is %10f\n", payFileOutput);
file.printf("Your amount entered for the payment method is %10f\n",
format.format(getPayment()));
if(totalCost<0){
file.printf("You still need: %5f per month\n",
format.format(getTotalCost()));}
else{
file.printf("\nYour budget seems good");}
file.close();
}
}
Exception in thread "AWT-EventQueue-0" java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4011)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2738)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2683)
at java.util.Formatter.format(Formatter.java:2449)
at java.io.PrintWriter.format(PrintWriter.java:878)
at java.io.PrintWriter.printf(PrintWriter.java:777)
at FinanceRev1.outputFile(FinanceRev1.java:173)
at FinanceGUI$button2Listener.actionPerformed(FinanceGUI.java:286)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
at java.awt.Component.processMouseEvent(Component.java:6175)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:5940)
at java.awt.Container.processEvent(Container.java:2105)
at java.awt.Component.dispatchEventImpl(Component.java:4536)
at java.awt.Container.dispatchEventImpl(Container.java:2163)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
at java.awt.Container.dispatchEventImpl(Container.java:2149)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
Update: the solution: Number format formatted the indicated number to a String, and because I had %f (float) it was pretty obvious I would get a stack since you cant reference a string to a float. Thanks to HydroKirby on MIrC.
In
file.printf("Your payment method is %10f\n", payFileOutput);
the type of payFileOutput is String, whereas the %10f format specifier is expecting to consume a float, hence your tip error:
java.util.IllegalFormatConversionException: f != java.lang.String
That particular line is one that would give rise to this error, but your calls to format() may also produce similar mismatches if the return type of that method were also String.

Categories

Resources