Spotify puzzle: avoiding exception handling error - java

I'm working on a Spotify puzzle (viewable here). I'm writing the solution in Java and I've gotten my code to pass their two example inputs in Eclipse, on ideone.com, and through Terminal on my osx, all without errors. However whenever I submit to the Spotify bot I get the following minimalist response:
We have tested your solution, and while doing so we unfortunately
discovered the following error: Run Time Error
An exception was not caught
Here's basically what I do to read in input:
scn = null;
try {
scn = new Scanner(System.in);
if(scn.hasNext()){
strIn = scn.nextLine();
//do work on first line of input
}
if(scn.hasNext()){
strIn = scn.nextLine();
//do work on second line of input
}
//do work on the rest of the lines
while (scn.hasNext()) {
strIn = scn.nextLine();
if(/*reached last line*/){
break;
}
}
}
catch(Exception e){
System.out.println("Exception caught");
System.out.println(e.getStackTrace());
} finally {
if (scn != null) {
scn.close();
}
}
You can view my complete solution here. Note that my actual submission declares my class public, as per the Spotify submission guidelines.
Since the problem requires only simple I/O from stdin to stdout, it seems like I only need to account for any exceptions that may be thrown when I'm reading in input within my try block. I provide a catch block for all Exceptions (bad form I know) but shouldn't that handle it? Maybe I'm neglecting some exceptions that could be popping up elsewhere?
It may be that I'm not accounting for some small peculiarity about how the Spotify bots parse input, but their response message and guidelines make it hard to pinpoint where exactly the problem is. I apologize if this question is too localized - other Spotify puzzle questions were seen this way - but I figure my i/o and exceptons questions are broad enough, and perhaps people have some good answers on how the Spotify bots might work. Also, it's been a while since I've coded in Java, so any other comments are certainly welcome.

Just to make it official, the exception that was being raised was not an I/O exception, like I was thinking, but actually an integer overflow exception. I needed to change the data type of the variable holding track plays to a long from an int. The test data Spotify was using must have had really large numbers that my ints couldn't hold, and that's why the program kept breaking! Hope this helps people.

Related

How can I add an error if the input doesn't match with it's variable

I just got into java programming today and I made a calculator that I'm so proud of as a first project even though I took many parts of it from the internet like the Scanner code and how to allow input for the user, but I don't know how to print out an error if the input doesn't match the variable assigned to, ex: user inputs a string instead of an integer,
You could use a try and catch statement to determine if the input you need is of the type that you want.
try {
// Block of code to try
}
catch(Exception e) {
// error if it's not the type you are looking for
}
As the answer above states you can use try and and catch and also create a custom exception but that won't really help you because just copying it won't make you understand it and there is a lot of concepts you should learn before you take a look at that.
If you want to learn how to code/learn java I can recommend you this video series by BroCode https://www.youtube.com/watch?v=NBIUbTddde4&list=PLZPZq0r_RZOMhCAyywfnYLlrjiVOkdAI1
It's really good for beginners and easy to follow along

Print all variables in Java exception? [duplicate]

This question already has answers here:
Dumping state of variables on Exception
(6 answers)
Closed 3 years ago.
Background:
I frequently write java code on Apache Spark for ETL job, usually on cloudera CDH cluster with every data source set up. The data I'm processing is usually dirty. For example for zip code, I was thinking I could use an integer to represent it but there could exists some record like "85281-281" and we couldn't parse it as a integer. Thus an exception is thrown and the program halt with a bunch of stack trace.
Previously I have to write the code based on my assumption, run it on the cluster, failed with a huge bunch of stack trace. Including the line number that throws the exception. But it is really time consuming to find the root cause especially I don't the specific line of the data.
So I'm think the following:
The code shouldn't stop when errors occurs. This is easy, use Java's exception handling system can easily achieve this.
I want to know the variables content in current stack which cause the error, so that I could find the root cause of the input (specific line in the input). Not just the line number that throws the exception. For example NullPointerException, I want to know the raw input data, which specific line in the input file caused this.
We have e.printStackTrace() to show the all function call in the stack trace. Can we do it better by also showing the content on top of the current stack? Just like a debugger do?
Of course I would manually print out all variables by hand coding. But I just want to know if there is a specific function that a debugger would use to show those variables.
For example, if you have the following code
final String line = ... // get next line
processLine(line);
you could transform it to
final String line = ... // get next line
try {
processLine(line);
} catch (RuntimeException e) {
System.out.println(String.format("Oh no, an exception! The line was '%s'", line);
e.printStackTrace();
// ... any recovery logic
}
You could catch not just RuntimeException's, but other exceptions as well. You could also log to some logger and not to console.

DataInputStream and DataOutputStream, compiles fine but does not run the way I wanted

I'm working on a program that takes user input in the form of a textfield and two comboboxes and displays the totals below. I have all of that working, but now I am trying to have the numbers selected saved and reread the next time the program is opened. I was lead to believe this is done with datainputstream and dataoutput stream.
I have coded both into my program and it compiles fine, but when I try to enter new data in, it catches it and closes (I coded the system.exit in to find out if its working or not).
I'm sure its something with my syntax, but I can't find it.
The whole program is here: http://pastebin.com/9L686Pxx
Edit: The formatting is a lot easier than I thought, so this is the block of code that is causing the program to exit.
try
{
int economyCount = input.readInt();
int standardCount = input.readInt();
int advancedCount = input.readInt();
int exceptionalCount = input.readInt();
int redCount = input.readInt();
int greenCount = input.readInt();
int blueCount = input.readInt();
int yellowCount = input.readInt();
}
catch(IOException io)
{
JOptionPane.showMessageDialog(null, "The program could not read the data. Please check the disk drive and then run the program again.", "Error", JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
You need to print out or log the stacktrace (or at least the error messages) for the exceptions that you are catching. Currently, your code is throwing away the evidence of what is causing the problem. (Hint: look at the javadoc for Exception.printStackTrace().)
Alternatively, run your application using your IDE's debugger, and set a breakpoint on the System.exit call that is causing the application to exit. Then examine the exception to find its classname and message.
The chances are that this will give you enough evidence to allow you to identify and fix the root problem. If not, add the complete stacktrace to your Question.
Based on the fact that the exception occurred at that point, I suspect that the problem is that you are attempting to read data that hasn't been written yet. It looks like the sequence is:
Open output ... which truncates the existing file.
Open input
Attempt to read 4 values from input. Ooops! Nothing there yet ... exception.
Once you have gotten past that, there are other problems with the way you are reading and writing:
Neither the read or write code seems to reset the data streams to the start.
The read phase is writing 4 ints and the write phase is writing 8 ints ... in a different order.
IMO, trying to reuse the same DataInputStream and DataOutputStream objects is a bad idea. You should recode it to, "open, read, close" and then "open, write, close" each time ... in the actionPerformed method. The input and output variables should be local variables, not instance variables.
The belated evidence of your stacktrace confirms this diagnosis.
If you're using DataInputStream.readFully() you need to catch EOFException separately. It means you've exhaused the input, so you should close it and stop reading.

Manual String Find and Replace [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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
Closed 9 years ago.
Improve this question
Given a string I #eat# #hamburgers# and a StringBuilder eat: [eat, consume, like] hamburgers: [hamburgers, spinach, bananas], I want to randomly replace the words within hashmarks with randomly chosen ones from their wordbanks, so that phrases such as I like bananas and I consume spinach will be generated. Code to randomly select another word, given a token (i.e. eat, hamburgers) has been written.
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
I need to somehow extract the first word within hashmarks and pass it to the method calling for its replacement before calling the method archetypeString(#[^#]+#, replacement) in such a way so that when the loop runs again, both the word grabber&passer-to method and the replacement method are then working with the second hashed word.
tokenizer dead-end:
StringTokenizer stt = new StringTokenizer(archetype);
while(stt.hasMoreTokens()){
String temp = stt.nextToken();
if(temp.charAt(0)=='#');
}
and the getPhrase method:
public List<String> getPhrases(StringBuilder fileContent, String token) {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(fileContent.toString()));
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // '['
do {
tokenizer.nextToken(); // go to the number
list.add(String.valueOf(tokenizer.sval));
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
It is not clear from your question whether this is part of some sadistic homework assignment or just the first way you thought of to solve whatever problem you're trying to solve. This is not a regular expression problem any more than it's a StringTokenizer problem.
Look at String.format(), and the formatting capabilities of Formatter. I do not understand why you would ever need to know what the last string you generated was if your object is to generate the next one at random. Just pick a new random value and format it with String.format().
--
After reading your comment to this answer and looking at the question you referred to, I'm going to make a couple of recommendations.
(1) start with a simpler coding assignment or two, something without regular expressions. Make sure you absolutely understand the following concepts: instance variables. variable scope. public methods versus private methods. passing parameters to methods, and returning values from methods. You can do quite a bit with just that much. You don't need to study inheritance until you have all of those down cold, and I recommend that you do not try.
(2) for each coding assignment for at least your first 5, make sure you have written out what your program is to be provided as data and what output it is supposed to produce. List any constraints someone has given you separately (must use class X, must display error message, whatever).
(3) Put opening braces and closing braces on lines by themselves; match each opening brace with a closing brace indented the same amount. Indent code within each pair of braces another 2 or 3 spaces further to the right. This means that brace pairs inside other brace pairs will be indented further. I know this is not the way you see most code, and plenty of people will tell you that it is "wrong". But until you get comfortable with scope and whether a given place in your code is inside or outside a method or a loop, I think it best that you give yourself these extra visual cues. For someone not familiar with other ways of doing things, this is easiest.
(4) be careful of your terms when posting here. In the other question you refer to, you say it is about inheritance, but it uses "implements", indicating that it is implementing an interface, not inheriting from a class. It is confusing to those of us trying to help you if you get the terminology wrong.
(5) when you post here: post the entire program (these early assignments should all be under 100 lines total, no reason not to post all of it). Make sure it is properly indented; use spaces instead of tabs. In text, and maybe also in comments, point out the place in the code where you seem to have the problem (if you know). If there is an error message, post the entire error message (don't tell us what it is, and don't try to interpret it for us). Work on your code until you have a specific question: why do I get a compile error here? Why do I get (or fail to get) this output? The program outputs X but I expected Y, why is that? etc.
We're not a tutorial shop; most of us need instruction to learn to program, and you need to get most of that somewhere besides here. We are willing to help with your questions, given that your questions are specific and reasonable and you aren't expecting us to provide the instruction. By itself, "I'm lost and need help" is a bit beyond StackOverflow's normal way of operating.

Source of Infinite Loop

Everytime I run this code, the console goes into an infinite loop printing "Please input a number". I do not understand why this is happening. Thanks in advance.
boolean check = true;
int temp = 0;
while(check==true){
try{
temp= asker.nextInt();
check = false;
}
catch(InputMismatchException e){
System.out.println("Please input a number.");
}
}
Edit: asker is a Scanner. The purpose of the code is to loop until an integer is inputted by the user.
The method asker.NextInt() is throwing an InputMismatchException, indicating that the input received from asker (assuming it's a Scanner) isn't actually an integer. This exception causes the loop to restart without setting check to false.
Print the exception within the catch block to get more information about the failure. But most likely, you're feeding your application something (lots and lots of something, if it's looping like that) that doesn't actually contain integer values.
You never want to actually "Use" try/catch--by that I mean don't use it as part of your program logic--this is what you are doing.
One big problem is that, like your app, you don't see the stack trace. Eating a stack trace in an exception is almost always wrong.
If you do have to catch an exception, handle it near the catch as well as you can, but it's better to set up your code so that the exception can't be thrown anyway.
Discard this advice if your teacher told you to do it this way, but remember in the back of your mind that it's poor form.
Also don't tell your teacher that it's poor form :) he either doesn't know in which case he won't understand why or he does know and is using this to show you how try/catch works.
What is asker, a Scanner? If nextInt() fails, it doesn't consume any input, so when you catch your exception and loop back around to try again, it ends up just reading the same bad input again.
You should do something in the catch block to consume the invalid input, so that the next time around, it can read some different input. Call asker.nextLine() maybe, and ignore the return value.
You need to break the loop and report why the loop occurs
boolean NotValid = true;
int temp = 0;
while(NotValid){
try{
temp= asker.nextInt();
NotValid = false;
break; // stop
}
catch(InputMismatchException e){
System.out.println("Please input a number. reason why:");
System.out.println(e);
NotValid = true;
}
}

Categories

Resources