prevent users for using certain characters in a calculator - java

i'm making a calculator and i want to throw a window with a message saying that only numbers are accepted in case that the user types a character which isn't a number in the textField, so this is what i did and didn't work at all.
Thanks for reading.
private void txtPantallaActionPerformed(java.awt.event.ActionEvent evt) {
String invalids;
invalids = "|##¢∞¬÷“”≠´‚πø ¥†®€æœå∫∂ƒ™¶§ ~–…„µ ß√©∑Ωqwertyuiopñlkjhgfdsazxcvbnm!$%&/=?¿*^QWERTYUIOPÑLKJHGFDSAZXCVBNM";
for (int i = 0 ; i < invalids.length() ; i++)
{
if(txtPantalla.getText().equals (invalids.substring(i, i+1)))
{
JOptionPane.showMessageDialog(null,"Only works with numbers");
}
}
}

You can use regex for readability and to avoid loop:
String value = txtPantalla.getText();
if(Pattern.matches(".*[^0-9].*", value)) {
// there are some invalid characters!
JOptionPane.showMessageDialog(null, "Only works with numbers");
}
Any solution that requires you to hardcode something is probably wrong.

Related

How can I remove a £ symbol from an array object and save it?

I'm coding a basic chatbot for a University project. I'm up to a point where the user must set a budget by entering an amount. At the moment, the program is able to search for a number in the user's message and save it correctly. However, when a £ sign is prefixed to it, it can't save as an integer due to having the pound sign in the message.
This is my code:
//Scan the user message for a budget amount and save it.
for (int budgetcount = 0; budgetcount < words.length; budgetcount++)
{
if (words[budgetcount].matches(".*\\d+.*"))
{
if (words[budgetcount].matches("\\u00A3."))
{
words[budgetcount].replace("\u00A3", "");
System.out.println("Tried to replace a pound sign");
ResponsesDAO.budget = Integer.parseInt(words[budgetcount]);
}
else
{
System.out.println("Can't find a pound sign here.");
}
}
I have previously tried .contains(), and other ways of indicating that it is a pound sign that I want to remove but I still get the "Can't find a pound sign here." print out.
If anybody can offer advice or correct my code I would appreciate it greatly.
Thanks in advance!
Strings in JAVA are immutable. You are replacing but never assigning back the result to words[budgetcount].
Change the following line in your code,
words[budgetcount] = words[budgetcount].replace("\u00A3", "");
Here is another way to do it by using Character.isDigit(...) to identify a digit and knitting a digit-only String which can later be parsed as an Integer,
Code Snippet:
private String removePoundSign(final String input) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isDigit(ch)) {
builder.append(ch);
}
}
return builder.toString();
}
Input:
System.out.println(removePoundSign("£12345"));
Output:
12345
You can also use String.replaceAll method.
Code snippet:
public class TestClass {
public static void main(String[] args){
//Code to remove non-digit number
String budgetCount = "£34556734";
String number=budgetCount.replaceAll("[\\D]", "");
System.out.println(number);
//Code to remove any specific characters
String special = "$4351&2.";
String result = special.replaceAll("[$+.^&]",""); // regex pattern
System.out.println(result);
}
}
Output:
34556734
43512

How would I condense these methods?

I couldn't figure out how to solve this problem using a single isValidPassword method so I broke it down into 3 and got it to work. Can someone explain to me how I could use the code I wrote and if possibly condense it?
Create a program Password that prompts for a password from the user and determines if the password is valid or invalid. There should be a static method isValidPassword that validates the password (String) and returns either true or false. A user has ONLY three tries to enter a valid password.
A valid password follows these three rules:
- Must have at least eight characters.
- Must contain ONLY letters and digits.
- Must contain at least two digits.
Use dialog boxes for the program. You must use the String and Character classes for this program. You may NOT use regular expressions. The program only needs to run once.
import javax.swing.JOptionPane;
public class Password {
public static void main(String[] args) {
int retryCount = 0;
while (retryCount < 3) {
retryCount++;
String password = JOptionPane.showInputDialog("Please Enter the Password");
if (CheckPassword(password)) {
JOptionPane.showMessageDialog(null, "Congrats! Correct Password!");
break;
}
else {
JOptionPane.showMessageDialog(null, "Sorry, Invalid Password, you tried " + retryCount + " times");
continue;
}
}
}
public static boolean CheckPassword(String password) {
if (password.length() >= 8 & CheckAlphanumeric(password) && Check2digits(password)) {
return true;
}
else {
return false;
}
}
public static boolean CheckAlphanumeric(String string) {
for (int i = 0; i < string.length(); i++) {
char x = string.charAt(i);
if (x < 0x30 || (x >= 0x3a && x <= 0x40) || (x > 0x5a && x <= 0x60) || x > 0x7a) {
return false;
}
}
return true;
}
public static boolean Check2digits(String string) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (Character.isDigit(c)) {
count++;
}
if (count > 2) {
return true;
}
}
return false;
}
}
Lets give a quick code review:
Read about java naming conventions. Method names go camelCase; and things that return boolean should be named like isPasswordValid() for example
What your are doing here is actually a good approach: one should prefer many small methods (that carry good meaningful names!) over having a few large methods (the thing behind is called the "Single Layer of Abstraction" Principle)
You could read about regular expressions in order to do most of that checking; especially checking for "ascii chars only" is a good candidate there! So even when your assignment says "dont use them"; you might want to learn how to use them. Just for your own learning progress! But as Kayaman pointed out, the Character class has many static helper methods for such checks; so there is no need to implement all of that manually.
Your code is "logically inconsistent". Your code is validating if some string adheres to certain password rules (minimum length, minimum number of digits). But your messages are implying that this code is checking if a provided password is correct; like in: user enters his password, and then code checks if that password is known and matching a previously stored password. In that sense: make sure messages and code content are consistent!
Beyond that; a suggestion how to enhance your design for "real world" usage. Thing is: there can be many many different rules that make a password valid. Which might change over time. And typically, you would want to tell your user which of that rules his input is conflicting with. One option to address these concerns:
public interface PasswordValidator {
public void checkPassword(String password) throws InvalidPasswordException;
}
Then you create various implementations, such as
public class MinimumLengthValidator implements PasswordValidator {
#Override
public void checkPassword(String password) throws InvalidPasswordException {
if (password.lenght() < 8) {
throw new InvalidPasswordException("Given password is not long enough; expecting at least 8 characters");
}
}
And then, you create instances of those different validator classes; and store them in some array. You iterate the array, and call each validation on its own; and when it fails, you directly receive an exception with a nice message for the user.
As said: the above is meant as inspiration only (and just typed down, so beware of typos).
Look at below code which may fulfill your all requirements-
This is pure java class. you can check logic from the below code.
program edit1 - To specify why password is incorrect.
public class Demo {
private final int passwordAttempts = 3;
private int countAttempts = 0;
private String password;
private int digitCounter = 0;
public Demo() {
init();
}
public static void main(String[] args) {
new Demo();
}
private String checkPassword(String pass) {
if (pass.length() >= 8) {
if (StringUtils.isAlphanumeric(pass)) {
char[] toCharArray = pass.toCharArray();
for (int i = 0; i < toCharArray.length; i++) {
char check = toCharArray[i];
if(Character.isDigit(check)){
digitCounter++;
}
}
if (digitCounter >= 1) {
return "success";
}else{
return "digit";
}
}else{
return "alphanumeric";
}
}else{
return "length";
}
}
private void init() {
while (countAttempts < passwordAttempts) {
password = JOptionPane.showInputDialog("Please Enter the Password");
digitCounter = 0;
String passwordResult = checkPassword(password);
if (passwordResult.equals("success")) {
JOptionPane.showInputDialog("yes you entered correct password...");
} else if(passwordResult.equals("length")){
JOptionPane.showInputDialog("password must contain atleast 8 characters...");
}else if(passwordResult.equals("alphanumeric")){
JOptionPane.showInputDialog("only alphanumeric password accept...");
}else if(passwordResult.equals("digit")){
JOptionPane.showInputDialog("password must contain atleast two digits...");
}
countAttempts++;
}
}
}
Now only you need to replace JOptionPane.showInputDialog() method with some other method which only specify message because showInputDialog() method prompts input text field also to enter value and we don't want this. I don't have idea any idea about swing.
Based on your comment -
This method returning string values like success,length,alphanumeric,digit ect. and below we are comparing this values with all above in if else if. whenever it get equal that means we have to show length message ,alphanumeric string message ,digit message accordingly.
Dependency -
I'm using maven. following dependency need to add into pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
If you are not aware about maven then simply download jar file from here and provide in lib folder of your project.

How can I check if my string is other than int's, to clarify i need to check it is not a number

... if instead of a number I get a letter, or a symbol, or 2 decimals.
I am making a change maker program in java.
Everything works good, the only thing i am confused about is checking the string to see if is invalid for my use,
I did this for when is left empty;
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "Invalid input! ");
System.exit(0);
}
That works perfect, now how can I do the else to check for letters or dots or symbols, anything that is not a number?
You could use regular expressions.
Here's some sample code to check for digits only (\\d) in your input string.
The code that actually checks is pattern.matcher(in).matches() and it tries to match the regular expression defined by regex
Let me know if you need more explanations
public class HelloWorld{
public static void main(String[] args) {
String regex = "\\d+";
String inputNumber = "2";
String inputDecimal = "2.0";
String inputString = "two";
String[] inputs = {inputDecimal, inputNumber, inputString };
Pattern pattern = Pattern.compile(regex);
for(String in: inputs){
System.out.print( in + " ");
System.out.print( pattern.matcher(in).matches()? "":"does not");
System.out.print( " contain integer numbers" );
System.out.println("---");
}
}
}
If you need to perform all the processing only when the String is integer why not check for integer value in the if clause and let the else clause be common for all the letter, dots, symbols and also empty.
if(s1.isNum){
//all processing here
}
else{
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Otherwise you could also use try and catch block.
try{
int num= Integer.parseInt(s1);
//rest of the processing
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Invalid Input");
System.out.exit(0);
}
Use either according to your requirement
You could use a regular expression1 and String.matches(String) which Tells whether or not this string matches the given regular expression. \\d+ should match one or more digits. Something like
System.out.println("12".matches("\\d+"));
Prints
true
1Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems. --jwz
To test whether it is an integer, parse it to an int like this:
Integer.parseInt(s1)
You might also want to make use of the value returned but I don't show it here. Now you can apply try catch blocks around the method call and catch NumberFormatException like this:
try {
Integer.parseInt(s1);
//The code here will run if s1 is an integer.
} catch (NumberFormatException e) {
//this will be executed when s1 is not an integer
}
You can also extract a method from the above code. A method that returns true when the exception is not thrown. However, a disadvantage of try catch is that throwing an exception needs time and thus, it slows down your program.
To test whether the string is a letter, you loop through all the chars in the string and use one of the methods of the Character class.
boolean isLetter = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isLetter(s1.charAt(i))) {
isLetter = false;
break;
}
}
If isLetter is true, it is a letter. Again, you can also extract this as a method.
To check whether it is a symbol, use one of the methods of the Character class (again).
boolean isSymb = true;
for (int i = 0 ; i < s1.length() ; i++) {
if (!Character.isJavaIdentifierStart(s1.charAt(i))) {
isSymb = false;
break;
}
}
To check for dots in a string, just use
s1.contains(".")
Isn't that simple?
Ok, I solved the problem the following way... I took a little bit of every idea lol...
if (s1 == null) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
if (s1.isEmpty()) {
JOptionPane.showMessageDialog(null, "You must enter a valid integer");
System.exit(0);
}
for (int i = 0; i < s1.length(); i = i + 1) {
if (!Character.isDigit(s1.charAt(i))) {
JOptionPane.showMessageDialog(null, "You must enter an integer value");
System.exit(0);
}
}

Checking if user entered anything?

I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}

How do I check an unknown amount of inputs java and stop checking at the end of a line

This is my first question. I am a second year computer science student and I'm having some trouble reading several inputs correctly. I'm creating a board game that accepts a line of commands.
This is what some of the problem code looks like:
User is asked to input a command like that could look like this: create 0 0 fast flexible, or like this: create 0 0, with the integers being of any value and fast or flexible being able to be entered without the other.
if((keyboard.next()).equals("create"))
{
xValue = keyboard.nextInt();
yValue = keyboard.nextInt();
if((keyboard.next().equals("fast")))
{
pieceType = "FP";
if((keyboard.next().equals("flexible")))
{
pieceType = "FF";
}
}
if((keyboard.next().equals("flexible")))
{
pieceType = "SF";
if((keyboard.next().equals("fast")))
{
pieceType = "FF";
}
}
}
The program consistently wants 7 inputs.
How do I make it stop checking for inputs after the user presses enter?
I guess you could split the whole string according to the white-spaces and then process the string sequentially by words (or parts). Anyway, you should assert the input as a whole carefully.
try with
String NEW_LINE_SIGN = "\n";
if (keyboard.next().contains(NEW_LINE_SIGN){ /* .... */ }
This should work...
Scanner kbd = new Scanner(System.in);
kbd.useDelimiter(System.getProperty("line.separator"));
//you could create a rule automatically with some kind of a rules engine
if(kbd.hasNext("create(\\s+)(\\d+)(\\s+)(\\d+)(\\s+)(fast|flexible)(\\s+)(fast|flexible)")) {
MatchResult res = kbd.match();
for(int i = 0; i <= res.groupCount(); ++i) {
System.out.println(res.group(i));
//handleRules(res.group(i), i);
}
}
kbd.close();

Categories