I'm writing a java program that adds two numbers with any length(the input is string). it works well but the judge gives me 44 because it has "Runtime Error"
what should i do?
To Answer your question "How to handle runtime-errors",
It is not different from any other exception:
try {
someCode();
} catch (RuntimeException ex) {
//handle runtime exception here
}
This judge may have given you a 44 (assuming that is low) because the input that comes to you as strings may not be numbers at all, and if this happens, your program should not crash? That would be my guess
UPDATE: Now that you have some code up, this is most likely the case, what happens if String a is "hello" ? Your program would crash at Long.parseLong(), you need to handle this!
Replace all your calls to Long.parseLong, by calls to such a method :
private long checkLong(String entry){
long result = 0;
try
{
result = Long.parseLong(entry);
}
catch(NumberFormatException e)
{
System.out.println("Value " + entry + " is not valid") ;
System.exit(1);
}
return result;
}
Related
So I have two boxes where you type in your numbers, and when clicked, it divides number one by number two and sets the label with the answer. (In a perfect world.)
However, you can also write down a word..
I got this for that:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// the String to int conversion happens here
numberOne = Integer.parseInt(jTextField1.getText().trim());
// print out the value after the conversion
System.out.println("int i = " + jTextField1);
}
catch (NumberFormatException nfe) {
System.out.println(nfe.getMessage() + " is not a number... ");
}
//numberOne = Integer.jTextField1
answer = calc.calculateNumbers(numberOne,numberTwo);
jLabel1.setText(answer);
}
Now instead of getting the error message in the console, I want the label (of the answer) to be set as message.
So, something like: jLabel.setText(ERROR MESSAGE)
but when I put it in the catch, I can't get it to work.
Thanks in advance!
The simple solution is to avoid catching the Exception too early and pretending it didn't happen.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = jTextField1.getText().trim();
try {
// the String to int conversion happens here
int numberOne = Integer.parseInt(text);
String answer = calc.calculateNumbers(numberOne, numberTwo);
jLabel1.setText(answer);
} catch (NumberFormatException nfe) {
jLabel1.setText(text + " is not an integer... ");
}
}
Try to place the catch after the code which you can't run if the exception occurs. Also avoid using fields when you could use local variables.
Reading #Peter Lawrey's comment, I realized I did
jLabel1.setText();
twice..
Looking like this:
catch (NumberFormatException nfe) {
System.out.println(nfe.getMessage() + "is not a number... ");
jLabel1.setText(nfe.getMessage());
}
answer = calc.calculateNumbers(numberOne,numberTwo);
jLabel1.setText(answer);
Apparently I COULD set the jLabel's text to something, but I overrode it with the second .setText();..
Thank you guys however!
I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)
I'm learning java and I'm trying to make a very simple application that does conversion of currency. You enter a rate, a direction (e.g : from euro to dollars or reverse) and an amount. the numbers valid non negative numbers.
So far I managed to make it so that the number can't be negative; now I need to throw an error if it's not a number.
I have following code:
public void setKoers(double koers)
throws NegativeValueException, NumberFormatException{
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
and my main looks like
try {
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
So how can I check if koers is a number or not.
I know I could put try and catch the error in my code, but I think this would go against the logic of where and how to deal with errors: in my main function I should catch any NumberFormatException
You do not need the NumberFormatException since Double.parseDouble() takes care of it for you. If it is not a proper number (in this case a Double) than the parseDouble() method will throw a NumberFormatException for you.
Here's how I would write it: (just take out the NumberFormatException)
public void setKoers(double koers) throws NegativeValueException {
if (koers > 0 ) {
this.koers=koers;
} else {
throw new NegativeValueException("negative number");
}
}
try{
cal.setKoers( Double.parseDouble(args[0]));
} catch(NegativeValueException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println( e.getMessage());
}
You will probably want to validate your input when the user tells the program to accept and process the input. In this portion of the code, you would convert the String to a number by parsing the input within a try/catch block, and then if an exception is encountered, notify the user of the error, prevent further processing, and perhaps clear any offending entry fields if present.
I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.
I am trying to terminate a program if the if statement returns that the file does not exist. At the moment the method is
public static void calcMarks()
{
String Assessment1 = null, Assessment2 = null, Assessment3 = null;
int mark1 = 0,mark2 = 0,mark3 = 0,sum = 0;
try {
File doc = new File ("marks.txt");
if(!doc.exists())
{
System.out.println ("Marks.txt Does Not Exist");
System.exit();
}
if(!marks.exists())
{
System.out.println ("TotalMarks.txt Does Not Exist");
System.exit();
}
Scanner input = new Scanner(doc);
while (input.hasNext()){
Assessment1 = input.next();
mark1 = input.nextInt();
Assessment2 = input.next();
mark2 = input.nextInt();
Assessment3 = input.next();
mark3 = input.nextInt();
}
input.close();
sum = mark1 + mark2 + mark3;
System.out.println(Assessment1 + " " +mark1 +"\n"+ Assessment2 + " "+mark2 +"\n"+ Assessment3 + " "+mark3+ "\n" + "Total" +""+ "=" + sum);
}
catch (FileNotFoundException ex) {
System.err.println("File has not been found");
}
}
but on the System.exit(); is the if statement, I get the error exit(int) in Jaba.lang.system. cannot be applied to ()
I have no idea what that means
You need to pass the return value in the exit() method.
Optimally, you should have System.exit( 0 );.
You can read this.
You must pass a status code (as an integer) to the System.exit() method. There is no argument-less version of this method.
The method's documentation:
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
Parameters: status - exit status.
You need to pass a return code to exit. Have a look at the documentation for java.lang.System. System.exit(-1); should work.
you need to enter an integer as a parameter for System.exit.
System.exit(0);
or
System.exit(1);
I'm not a Java programmer, but it looks to me like System.exit() should have an exit code. Try this:
System.exit(0);
System.exit(int) requires an integer argument:
System.exit(1);
The operating system is expecting an Exit Status to report to the program that spawned your program.
A further nitpick: you are looping over input, storing it into variables, and then doing nothing with those variables until the end of your loop. You will throw away all but the last input to your routine. So when you go looking for that bug, you'll know where to look. :)
If I remember right with java an argument must be passed to. This serves as a debugging tool so you can easily tell what part forced the program to exit. without having to print anything out. Generally one would use 0 for any successful exit and any other predetermined values by the programmer as an "error code." So without any further explination you would want to change your exit call to something like the following:
System.exit(0); //This would be for a programming successfully running and exiting.
or
System.exit(X); //Where x is any int to signal a program failure