How would I get a specific number range from a textfield? - java

I'm currently working on a search method in school and I'm stuck in a newbie mistake.
I havent been programming for long and I tried searching the internet for solutions but couldnt find any. I would need to get a number range from 1-10 from the textfield and then put it as an int. Once I've done that I would have to send it to my search method which I am working on. Thanks in advance peeps.
String Value = txfSort.getText();
int NumberValue = Integer.valueOf(Value);

Probably you should first limit the input of textFields to nummeric values. You can help your self with question here: What is the recommended way to make a numeric TextField in JavaFX?
public class NumberTextField extends TextField
{
#Override
public void replaceText(int start, int end, String text)
{
if (validate(text))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (validate(text))
{
super.replaceSelection(text);
}
}
private boolean validate(String text)
{
return text.matches("[0-9]*");
}
}
Code by: Burkhard
Above code would automaticly check on entry if input is ok. So then you just check, if value is > 0 and < 10. If that is true you just call your method and use value of textField.
One way of doing described would be this:
int value = Integer.valueOf(txfSort.getText());
if(value > 0 && value < 10)
{
myMethod(value);
}

try that one:
textField.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent e) {
char caracter = e.getKeyChar();
if (((caracter < '0') || (caracter > '9')) // for numbers only
&& (caracter != '\b')) {
e.consume();
}
if (Integer.valueOf(textField.getText() + caracter) > 10) {
e.consume(); // if on the text field the numbers are bigger
// than 10, consumes the last number typed
}
}
});

Related

JTextfield Validation for numbers?

I am trying to validate my roll no (input of integer value) from JTextField. Well my code is compiling but while running it is giving me an error NumberFormatException.
Here is my validation code
public int rno_vd() {
int a=0,b=0,c=0,x=0,y=0;
int vrno =Integer.parseInt(txtRno.getText());
String r = String.valueOf(vrno);
if (r.isEmpty()) {
JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;
}
else if (Pattern.matches("[a-zA-Z]+",r)) {
JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;
}
else if (vrno < 0) {
JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;
}
System.out.println(a + b + c);
if (a==1 || b==1 || c==1) {
x=1;
return x;
}
else {
y=0;
return y;
}
}
error
C:\Users\Hp\Desktop\jproject>javac -cp hibernatejar\* *.java
Note: DBHandler.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\Users\Hp\Desktop\jproject>java -cp hibernatejar\*;. Sms
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at AddFrame.lambda$new$1(AddFrame.java:80)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
It is getting NumberFormatException, when text field has empty value.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Could you please try to validate the text first, and then parse the string?
// Validating text input first
String r = txtRno.getText();
if (r.isEmpty())
{JOptionPane.showMessageDialog(null,"rno should not be empty");
a=1;}
else if (Pattern.matches("[a-zA-Z]+",r))
{JOptionPane.showMessageDialog(null,"rno should be in digits");
b=1;}
else if (vrno < 0)
{JOptionPane.showMessageDialog(null,"rno cannot be negative");
c=1;}
// Converting to int, if validation is successful
int vrno =Integer.parseInt(txtRno.getText());
Komal here as I can see you want to validate JTextField for roll numbers ie should only contain integers, any other character instead of numbers should not be accepted...
Well, I suggest you to try validating on every keyReleased using KeyListener of KeyEvent.
Every key you press is validated if its number its good to go if its not it will show Dialog box saying "only numbers accepted".
I am sharing my code I hope it might help
//********function to check if value is numric or not*********
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e){
return false;
}
}
//************************function ends******************************
//txtRno is my JTextField
txtRno.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e)
{
//code
}
public void keyReleased(KeyEvent e)
{
String value = txtRno.getText();
int l = value.length();
if(!isNumeric(value) && l>0){//if not numric it will not allow you to edit JTextField and show error message
txtRno.setEditable(true);
JOptionPane.showMessageDialog(c,"You need to enter number","ERROR",JOptionPane.ERROR_MESSAGE);
txtRno.requestFocus();
txtRno.setText("");
txtRno.setEditable(true);
lblError.setText("");
}
else { //else it will take the input as it already number or integer
txtRno.setEditable(true);
lblError.setText("");
}
}
public void keyTyped(KeyEvent e)
{
//code
}
});

how to get calculator to accept new numbers after equal sign is pressed? java

i am doing an exercise to create a simple calculator in java.
i want the calculator to keep taking numbers after the equal sign is pressed. so if i press "10+10 =" the result will be 20, and if I want to press "+1 = " and the result will be 21. or if I want to subtract as well.
my code is below. im sure the change has to be made to the "equals" portion of the code but i am unsure where/how to begin.
public int getDisplayValue()
{
return displayValue;
}
public void numberPressed(int number)
{
currentValue = (currentValue * 10) + number;
displayValue = currentValue;
}
private void applyPreviousOperation()
{
if (previousOp == '+')
{
heldValue = heldValue + currentValue;
displayValue = heldValue;
}
else if (previousOp == '-')
{
heldValue = heldValue - currentValue;
displayValue = heldValue;
}
else {
heldValue = currentValue;
}
}
public void plus()
{
applyPreviousOperation();
previousOp = '+';
currentValue = 0;
}
public void minus()
{
applyPreviousOperation();
previousOp = '-';
currentValue = 0;
}
public void equals()
{
applyPreviousOperation();
previousOp = ' ';
currentValue = 0;
heldValue = 0;
}
public void clear()
{
displayValue = 0;
previousOp = ' ';
}
}
You need to define your question more clearly.
what's the calculator flow should be. You describe an operation that contradicts a simple a+b.
It really matters how you input the numbers, If for example the very first operation is texted "a+b" ,"a-b" .... than you can keep it as currentValue.
than next opperations will be calculated against currentValue.
Have a variable called defaultOperand. When the equals button is pressed, update the defaultOperand variable with the output of the operation. It becomes the default left side operand. If an operation is inputted without a left side operand, then use the value in the defaultOperand as the default left hand operand.

Searching for a specific number in a int variable

I'm currently "learning" JavaScript + Android Studio for school and I got a little problem for which I can't find the right answer on Google:
I want to know if an int variable has a specific number, for example, I'm looking for the number 7 now int numberOne = 25824 doesn't have a 7 inside, but int numberTwo = 12387 does have one. Is there a way to search for a specific number in int variables?
I tried converting the int into a new string variable, but somehow this doesn't work :(
Here's some code I'm working with:
public int round = 1;
public String nummerSieben = "" + round;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (round % 7 == 0 || nummerSieben.contains("7")==true) {
....
} else {
....
}
}
});
Thank you for your help!
public int round = 1;
public String nummerSieben = "" + round; // nummerSieben is now "1"
You're hard-coding the value of nummberSieben. You need presumably get some value from the view, and test that. If you get it as in int, use
Integer.toString(i).contains("7") // i is whatever number you get from your view.
If you get it as a String, then half the work is already done, and you just need
i.contains("7")
As noted above, this has nothing to do with JavaScript - both your example and my answer are in Java.
Couple of things:
Your comparison is not right, method String:contains() returns a boolean,
Module % does not assert you the number will contain 7 or one of it's multiples.
Integer.toString(value) converts easily your int to String.
Knowing this, you can do:
if (Integer.toString(round).contains("7")) {
// IT CONTAINS THE NUMBER!
} else {
// IT DOES NOT CONTAIN THE NUMBER
}
Here is perfect solution of your problem
public class Finder {
static int round = 123456789;
static String str = String.valueOf(round);
public static void main(String... args) {
if (str.contains("7")) {
System.out.println("Found");
} else {
System.out.println("Can't found...");
}
}
}
Just convert your integer to String and then try to found the specific value from that string.
You don't have to convert to string in order to search specific digit in integer.
You can use math for that purpose.
Here is the code:
private static boolean isFound(int round) {
while (round > 0) {
if (round % 10 == 7)
return true;
round /= 10;
}
return false;
}
basically what this code do is checking each last digit if it's equals to 7 if not he divides the num by 10 and remove the last digit and after checking again, it will do so until no digit left (num=0) or he will find 7.

What is the best way to verify multiple jcombobox item selection?

What is the best way to verify if a specific combination of two symbols is already selected in a several couples of jcomboboxes? This question is refered to a situation in which I have e. g. 10 options and for each of those I can assign a combination of two symbols where first one is from [ALT, CTRL, SHIFT] vector and second one is from [letters and numbers] vector. Both vectors are visualized in JComboBoxes (for each option are two combo boxes).
Put couples of jcomboboxes into different buckets. Those couples that have ALT selected in first combobox go to the 1st one, those who have CTRL selected - to the 2nd one, SHIFT - to the 3rd one. Then see whether the same option in the second combobox is selected within the buckets.
Thank you everyone for answers. Finally I manage this problem this way:
// Method For KeyGroup 1
public boolean isAlreadyKeyEvent(int index) {
int vector[] = {combo_1_group1.getSelectedIndex(), combo_2_group1.getSelectedIndex(), combo_n_group1.getSelectedIndex()};
int x = 0;
for (int i : vector) {
if (i == index) {
x++;
}
}
if (x > 1) {
return true;
} else {
return false;
}
}
// Method For KeyGroup 2
public boolean isAlreadyInputEvent(int index) {
int vector[] = {combo_1_group2.getSelectedIndex(), combo_2_group2.getSelectedIndex(), combo_n_group2.getSelectedIndex()};
int x = 0;
for (int i : vector) {
if (i == index) {
x++;
}
}
if (x > 1) {
return true;
} else {
return false;
}
}
combo_1_group2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean one = isAlreadyKeyEvent(combo_1_group2.getSelectedIndex());
boolean two = isAlreadyInputEvent(combo_1_group1.getSelectedIndex());
if (one) {
if (two) {
JOptionPane.showMessageDialog(null, "Such shortcut already exists! \n" +
"Choose something else.");
combo_1_group2.setSelectedIndex(Settings.combo_1_group2);
} else {
Settings.combo_1_group2 = combo_1_group2.getSelectedIndex();
}
} else {
Settings.combo_1_group2 = combo_1_group2.getSelectedIndex();
}
}
});
So basically I've wrote two quite similar methods and also I've created a new class with static fields for values store. All works great :)

How to character and Numeric values restrict in TextField Java

I have two questions regarding character and numeric values limitation. I have listening to focus lost events and validating Name (character) and Contact (numeric) TextFields.
1. How do I restrict numeric data less then 3 digits and not allow more then 13 digits.
Below is the coding of my contact TextField for numeric:
private void txt_contactFocusLost(java.awt.event.FocusEvent evt) {
if (txt_contact.getText().equals("")) {
} else {
String contact = txt_contact.getText();
Pattern pt6 = Pattern
.compile("^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]+$");
Matcher mh6 = pt6.matcher(contact);
boolean matchFound6 = mh6.matches();
if (!(matchFound6)) {
JOptionPane.showMessageDialog(null,
"* Enter the Numaric Values only *");
txt_contact.setText("");
txt_contact.requestFocus();
}
}
}
2. How do I restrict character data less then 3 character and not allow more then 30 characters.
private void txt_nameFocusLost(java.awt.event.FocusEvent evt) {
if (txt_name.getText().equals("")) {
error2.setText("Enter Full Name");
txt_name.setText("");
} else {
String name = txt_name.getText();
Pattern pt1 = Pattern.compile("^[a-zA-Z]+([\\s][a-zA-Z]+)*$");
Matcher mh1 = pt1.matcher(name);
boolean matchFound1 = mh1.matches();
if (!(matchFound1)) {
JOptionPane.showMessageDialog(null,
"* Enter the Character Values only *");
txt_name.setText("");
txt_name.requestFocus();
} else {
error2.setText("");
}
}
}
You can do something easier:
NumberFormat numF = NumberFormat.getNumberInstance();
numF.setMaximumIntegerDigits(13);
numF.setMinimumIntegerDigits(3);
JFormattedTextField THE_FIELD = new JFormattedTextField(numF);
(The same idea for characters)
Now, only numbers are allowed, with the specified length range.
Read more about it: NumberFormat and JFormattedTextField
in the pattern you can use the statement {n,m} n- to m- times
Duo to this you can build your pattern like this
for your charackter comparison
Pattern pt6=Pattern.compile("[a-zA-Z]{3,30}"); // it says, it should be 3-30 non Digits
for the numbers it is
Pattern pt6=Pattern.compile("\\d{3,13}"); // it says, it should be 3-13 Digits
For String
public boolean validateString(String data){
char [] chars = data.toCharArray();
if(chars.length < 3 || chars.length >13)
return false;
return true;
}
For Number
public boolean validateNumber(int number){
String data = number+"";
return validateString(data);
}
I'm using this one. very simple and easy
use the method that you need or both then call where you need pass your JTextField as parameter done...
public static void setNumericOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((!Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
public static void setCharacterOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}

Categories

Resources