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. :)
Related
Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}
This question already has answers here:
How do I exit a while loop in Java?
(10 answers)
Closed 5 years ago.
I am new to Java and programming in general. I've encountered not exactly a problem, but more like a wall of my ignorance. On my QA Automation courses I was asked to write a simple calculator program in Java, I kept it very basic - you needed to launch the program over again every time you preformed a calculation. I learned about while loops and it seemed the while loop was a good solution to keep the program running. But now I am at another extreme - the loop is infinite. My question is: is there any simple way to exit the program without re-writing the code and the way I've structured my calculator? I don't know how to do it but it would be nice if program would end when user presses [Esc] or prints "Exit". Is there a simple way that I (beginner) would understand and could implement?
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int first, second, answer;
String operator;
Scanner s = new Scanner(System.in);
try {
while (true) {
log("Please enter a math equation using +, -, * or /");
first = s.nextInt(); //User enters first number
operator = s.next(); //User enters operator
second = s.nextInt(); //User enters second number
if (operator.contains("+")) {
answer = first + second;
log("" + answer);
}
if (operator.contains("-")) {
answer = first - second;
log("" + answer);
}
if (operator.contains("*")) {
answer = first * second;
log("" + answer);
}
if (operator.contains("/")) {
if (second == 0) {
log("You can't divide by 0");
} else {
answer = first / second;
log("" + answer);
}
}
}
} catch (java.util.InputMismatchException error) {
log("Incorrect input");
}
}
public static void log(String s) {
System.out.println(s);
}
}
Thank you, if you can help me!
P.S. I don't know if it is a correct way to handle exceptions or a very ugly one. I'd appreciate if you could comment on that too.
Yes, use break:
if(endingCondition)
break;
This will break out of the innermost loop.
In order to follow your example and not deviate from it focusing on other code improvements, you should have to change the way you read the parameters, because the way you do it now, you could never read the exit word to get out. In order to do this you can use the following approach:
This will add a new string parameter to read the exit or the first operand (in string format). Then, it will transform it into an int:
int first, second, answer = 0;
String operator, firstParam = "";
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.println("Please enter a math equation using +, -, * or /, or exit if you want to stop the program");
firstParam = s.next(); //User enters first number or exit
// This first param is read as a String so that we are able to read the word exit
if(firstParam.equals("exit"))
break;
first = Integer.valueOf(firstParam); // This will transform the first parameter to integer, because if it reaches this point, firstParam won't be "exit"
//[... Rest of your program...]
}
} catch (java.util.InputMismatchException error) { ... }
TIPS FOR ERROR HANDLING
1: You don't have to specify the complete reference of the InputMismatchException while in catch block because you have already imported the java.util package
catch (InputMismatchException e)
{
//handle exception here
}
2: In case you are unsure about the type of Exception that can thrown, just catch the object of class Exception. Since Exception is the super class for all the Exceptions, it can handle all exceptions.. This would work perfectly for beginners.
catch (Exception e)
{
//handle exception
}
3: You can handle multiple exceptions for the same try block, each catch handling a particular type of exception. Give it a try.
FOR EXITING THE LOOP
if (s1.contains("EXIT"))
break;
Here s1 is the string, and if the string contains the word EXIT (ALL CAPS ONLY), the loop will terminate.
I have some EditText in my Activity. The user has to fill them out and confirm his input. Some of the EditText are only for numbers. To make sure that there are only valid values i'm trying to cast the input to an Integer using Integer.parseInt( . . . ). The problem is no matter what the string is the NumberFormatException wont be thrown. I debuged the problem and the corosponding line is executed every time but without throwing an exception.
Here is the Code of my method:
private boolean formNotEmpty()
{
boolean returnValue = true;
for(int i = 0; i < _editText.size();i++){
if(_editText.get(i).getText().toString().trim().length() == 0)
{
returnValue = false;
_toastMessage = "Es müssen alle Felder ausgefüllt werden.";
break;
}else if(_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userPLZ))
||_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userTelefon)))
{
try{
Integer.parseInt(_editText.get(i).getText().toString().trim());
}catch(NumberFormatException e)
{
_toastMessage += "In "+_editText.get(i).getHint().toString() +" dürfen nur Zahlen stehen. \n";
}
}
}
return returnValue;
}
I've forgotten to set returnValue in the catch block to false. The _toastMessage gets a new string if the method returns true. This is the reason i assumed that the exception is never thrown. I'm realy sorry for the trouble i caused.
Thank you very much
If you are counting on the code to throw you an exception, and you want to use this as a means to validate the data to accept only numbers, then this is not the right approach to this. Exception handling should'nt explicitly be used as an if-else like you suggest. A simpler, and perhaps more correct way to accomplish what you want would be :
Declare in the layout xml
android:inputType="number"
for that particular edittext you want to confine entries only to numbers.
When you do this, you only get option to type in numbers, when you try to fill that editText, as a user. After adding this in the xml, you would not need to depend on the Integer.parseInt() API to throw exception, for your validation.
Also you can use the attr of EditText:
android:digits="0123456789."
http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits
After that user can write only numbers.
I'm making a jTextField restrict integer input in netbeans and I don't know what to do.
I'm doing it like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
try {
String j = (String) txtName.getText();
} catch ("Which Exception to Catch?") {
if (!txtAge.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null,
"Please enter string values");
txtAge.setText(txtAge.getText().replaceAll("[^a-z]", ""));
}
}
}
What should I put on the catch?
You could just test the input against a regular expression using String.matches() to make sure it's only digits (no need to catch an exception such as a NumberFormatException - it can be considered bad practice to provoke exceptions to validate conditions).
String j = txtAge.getText();
if (!j.matches("\\d+")) {
// It is not a number
}
If you just want to try to convert to an Integer directly and catch an exception you should use Integer.parseInt() (it will throw a NumberFormatException if the input can't be parsed as an Integer):
String j = txtAge.getText();
try {
Integer i = Integer.parseInt(txtAge);
}
catch (NumberFormatException e) {
// j isn't a number...
}
EDIT: There seems to be a little confusion with the answer you provided. In your question the error message was Please enter integer values, as if valid input was only digits. In the answer you posted the message was Please enter String values.
If you want to validate the input doesn't have any numbers, you'll have to use another regex, such as .*\\d.*". If it matches, it means it has a digit. Or you could also use \\D+ to ensure it has one or more non-digits.
I've solved my problem like this:
private void txtNameKeyReleased(java.awt.event.KeyEvent evt) {
String j = (String)txtName.getText();
if ( j.matches("\\d+") && !txtName.getText().isEmpty()) {
jOptionPane1.showMessageDialog(null, "Please enter String values");
txtName.setText("");
} }
Thanks for the ones who tried to help me :)
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.