Find Exception caller and modify to display a value - java

Suppose I have 3 TextFields - used for users to input values into (when the program is running):
TextField input1 = new JTextField("00");
TextField input2 = new JTextField("00");
TextField input3 = new JTextField("00");
When the user inputs values, the program then takes those values and stores them as Integers (for operations later on):
public void actionPerformed(ActionEvent e) {
String temp1 = input1.getText();
String temp2 = input.getText();
String temp3 = input3.getText();
int num1=0, num2=0, num3=0;
if(e.getSource() == storeButton){
try{
num1 = Integer.parseInt(tem1);
num2 = Integer.parseInt(temp2);
num3 = Integer.parseInt(temp3);
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Input must be an integer from 0 to 50");
}
}
}
As the above code shows, when the user clicks the storeButton the values in the TextFields are parsed into the specific variables as integers and if any of the TextFields contain an input besides an integer, a message will pop up.
The question:
When the exception is called, how do I clear (set to "0") the TextField that does not contain a number? The TextFields that contain an integer must not be cleared.
I can do that by using try and catch for each of the TextFields when parsing as integers but that would mean too much repetition of code (especially when there are many TextFields).

Take a look at Character.isDigit(). You could make a sub-method that loops through each String and checks it to see if it is a digit.
Alternatively, you could use a regex on the String to check if it is a digit.
This lets you get rid of the try/catch and handle them with if/else.

Related

keyTyped gives JTextField blank

can't solve this problem.
I want to retrieve the text that I write on my textfield with keyTyped and put int on a String. But If I do it, it gives me a blank String. What can I do?
textField_9.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
xw = textField_9.getText(); //should retrieve my input
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if((!(Character.isDigit(c)) && (c!='.'))){
e.consume();
}
System.out.println(xw); //gives nothing ("") not null
numero = e.getKeyChar();
String fileName = defaultx+"\\"+"Contratti"+"\\"+textField_7.getText()+"\\"+"lista"+tipo;
Scanner scanner;
try {
scanner = new Scanner(new File(fileName));
scanner.useDelimiter(":");
while(scanner.hasNext()){
num = scanner.next();
System.out.println("Numero = "+num+"\t"+xw); //debug
dat = scanner.nextLine().replaceAll(":", "");
if(num == xw){
try(Scanner scanner1 = new Scanner(dat)){
scanner1.useDelimiter(":");
giorno = scanner1.next();
meset = scanner1.next();
anno = scanner1.next();
System.out.println(giorno+"-"+meset+"-"+anno); //debug
}catch(NoSuchElementException ex){
}
}else{
System.out.println("Dato non trovato");
}
}
scanner.close();
} catch (FileNotFoundException e1) {
} catch(NoSuchElementException e1){
}
}
});
Example
I write into my JTextField the number "5" , xw should be then "5" but instead it will be ""
Basically what I'm trying to do is to read user's input, this input (that's a number) will be searched in a .txt file that contains a list of number and dates. example : 1st line of the .txt file is "1:1-01-2017" the second line is 2:8-01-2017" the third line is "3:15:01:2017 etc..
Read this data in once not with each key press as you're trying to do above, perhaps doing this in the class's constructor. Then store the data in a searchable collection, perhaps an array list of custom class.
so what I want to do is to search in this .txt file that number before ":" and when it finds it ,write in another textfield the date. example. user write in textfield1 "3", the program will search in the .txt file the number 3 that is before the ":" and when it find it , will write the date into another textfield.
The custom class that holds the text file's data should hold the separate numbers in their own fields, and again, search the ArrayList of these objects when needed.
Also:
do not add a KeyListener to a JTextField as this can prevent the JTextField from behaving correctly (as you're finding out).
We sometimes add a DocumentListener or a DocumentFilter to the JTextField's Document for similar behaviors...
But in your case I wouldn't do either. Instead add an ActionListener to the JTextField, a listener which is activated when the ENTER key is pressed, and search the ArrayList from within this listener.
You should almost never have empty catch blocks as we see in your code above. At least print out the stacktrace, as you could very well be having problems from exceptions being thrown completely without your knowledge since your code ignores them.

How to capture non-integers in this Java program

How do I add a try-catch piece of code to stop someone from entering chars or, as a matter of fact, anything other than an int from 1 - 5?
boolean valid;
int option = 0;
do {
Scanner in = new Scanner(System.in); // need try catch
menu();
System.out.println("\n");
option = in.nextInt();
valid = option > 0 && option < 6; // try / catch needed around here?
} while(!valid); // stop chars and strings being entered
// I want to stop the user entering anything other than an int 1-5
if you need that number to check which option the user entered you dont need to do that. all you have to do is change the option variable from int to String and your if statements from
if(option==1) to if(option.equals("1"))
if you are going to need real ints for real mathematical equations then Sheetals answer will be more appropriate, but for a menu input, Strings are just fine.
dont forget that you can have String comparison with that contain numbers
"1"<"2" is true
Use string to enter the choice and then parse it using Integer.parseInt() function.
Scanner in = new Scanner(System.in);
String choice = in.next();
try{
int intChoice = Integer.parseInt(choice);
if(choice > 5){
throw new Exception("Can't be more than 5");
}
}catch(Exception e){
System.out.println(e.printStackTrace);
}
Why not read the token as a string and use Integer.parseInt(), ignoring tokens that cannot be parsed as an integer. If not then handle it

Continually Validating Integers

I have a method I'm using to validate user-inputted values in a program. Whenever the user inputs a string into a JOptionPane, I call this method and pass in the inputted string, plus the maximum and minimum values I need their input to be between. First I check if the input is an integer by trying to parse the input string and catching exceptions, then I check if the integer is between the min and max. My problem is that if the user inputs another incorrect non-integer value after being prompted, I don't know how to check if the new value is correct or not. Here is the method, can anybody help?
int checkInput(String input, int min, int max) {
Boolean isInteger = false;
Boolean inputAccepted = false;
int userInput = 0; //will be set later
while (!isInteger) {
try
{
userInput = Integer.parseInt(input);
}
catch (NumberFormatException e)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
isInteger = true; //the problem here is that it assumes the user inputted a correct value after being prompted... what if they enter another incorrect value?
}
}
while (!inputAccepted) {
if (userInput < min || userInput > max)
{
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please enter only integers between " + min + " and "+ max + "."));
}
else
{
inputAccepted = true;
}
}
return userInput;
}
I believe the main problem is that you have a method whose job isn't simple and well-defined. It looks like you have a statement outside this method that inputs a number; but checkInput has two jobs: making sure the number is valid, and inputting more numbers until it is. This is a problem in two ways: your code that does the input is duplicated in two places, and you have a method whose responsibility isn't clear.
Instead, try writing a method that just checks whether the input is valid, and returns true or false. I'd change the name to isValidInput. The caller would then have a loop that would perform the input, make sure it's valid, and go back if it isn't.
Usually I wouldn't answer a question like this by pointing to flaws in your design. But I think that in this case, if you rethink your design, your question will answer itself. (That's often the case when you design things correctly--things fall into place.)
Your checkInput() function should throw its own exception if the input is not correct. Spliting the code into a validator and a parser would result in parsing the input twice.

How do i make a check for in the input is a number or not in swing?

So i was making an application where the user enters an input, and when he clicks the button it executes a command, however the input has to be an integer, so i added a check but even when i enter an integer is gives me an error saying "you can enter numbers only!"
heres my code :
String itemId = textField1.getText();
String itemAmount = textField2.getText();
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);
if (!Double.isNaN(id) || !Double.isNaN(amount)){
JOptionPane.showMessageDialog(
null, "You can only enter numbers!"
);
even after i enter numbers to the textFields i still cannot pass this test, why and how can i fix this ? thanks.
however the input has to be an integer, so i added a check but even
when i enter an integer is gives me an error saying "you can enter
numbers only!"
there are two ways, to use
JFormattedTextField with number formatter, JSpinner with SpinnerNumberModel
add DocumentFilter to JTextField
Actually you can just do it like this:
String itemId = textField1.getText();
String itemAmount = textField2.getText();
int id;
int amount;
try{
id = Integer.parseInt(itemId);
amount = Integer.parseInt(itemAmount);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}
If itemID and itemAmount value is not parse-able, means non-digit was entered
Double.isNaN(id)
Returns true if the specified number is a Not-a-Number (NaN) value,
false otherwise.
But your id and your amout are Integers so it will return false and you do !Double.isNaN(id) and invert the boolean, so the result is true. Its only an logical failure. Remove the !.
if (Double.isNaN(id) || Double.isNaN(amount)){
JOptionPane.showMessageDialog(null, "You can only enter numbers!");
}
Note:
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);
Sourround this two lines with an try and catch block, otherwise you will get an NumberFormatException if the input is not numeric.
try
{
int id = Integer.parseInt(itemId);
int amount = Integer.parseInt(itemAmount);+
}catch(NumberFormatException e)
{
//print your error here
}
Use Apache's StringUtils.isNumeric() method, if you don't want to use JFormattedTextField

reading user input and detecting type of entry in Java

In my program, I have a JTextField reading the user input. The user is supposed to enter a number and then click a JButton to confirm the entry, but i want to have a catch where if the user does not enter a number, a pop-up appears telling the user it is an incorrect input. How would I implement something to detect whether or not the user enters a number when the JButton is clicked? if i need to give more code, let me know.
JButton okay = new JButton("OK");
JTextField dataEntry = new JTextfield();
okay.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
firstEntry = Float.parseFloat(dataEntry.getText());
//want to see if it's a float, if true, run the following code
confirm = true;
changeText();
dataEntry.setText("");
}
});
parseFloat throws a NumberFormatException if the passed String does not contain a parseable float. You can catch this exception to detect whether the user has entered a float:
try {
firstEntry = Float.parseFloat(dataEntry.getText());
} catch (NumberFormatException e) {
// input is not a float
}
Another option is to use a Scanner if you don't want to be handling exceptions:
Scanner scanner = new Scanner(dataEntry.getText());
if (scanner.hasNextFloat()) {
firstEntry = scanner.nextFloat();
} else {
// input is not a float
}
I would avoid of using catch-mechanism of exceptions to check if the value is a number because this is a very expensive procedure in java.
It would be better if you use FormattedTextFields: formattedtextfield
This needs some code but is a very elegant solution. You can also write your own formats with this concept.

Categories