NumberFormatExceptions - java

I am trying with a Utility function to get int and check if bad input results in
NumberFormat Exceptions,is there a way to work with Non-decimal Int for below function
//--- Utility function to get int using a dialog.
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
val = Integer.parseInt(s);
break; // exit loop with valid int
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}
//end getInt

If I understand you... maybe you can do this:
public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
if(mess.match("^\d+$")){ // Check if it's only numbers (no comma, no dot, only numeric characters)
val = Integer.parseInt(s); // Check if it's in the range for Integer numbers.
break; // exit loop with valid int
} else {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}

Try what u want , one for decimal checker and one for non-decimal int
// for deciaml
public static Boolean numberValidate(String text) {
String expression = "^[+-]?(?:\\d+\\.?\\d*|\\d*\\.?\\d+)[\\r\\n]*$";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}
// non-decimal int
public static Boolean numberValidate(String text) {
String expression = "[a-zA-Z]";
CharSequence inputStr = text;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
MatchResult mResult = matcher.toMatchResult();
String result = mResult.group();
return true;
}
return false;
}

Related

How can I get TextField input by using ArrayList

I need to test a method that takes an input TextFild, how can I change the input to ArrayList to get the data. I am getting an error that says
java.lang.ClassCastException: class java.lang.Character cannot be cast to class
private boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
Matcher matcher = p.matcher(passwordField.getText());
if (matcher.matches()) {
return true;
} else {
lblMessage.setText("Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
my solution
public class TestCases {
ArrayList<Character> characters = new ArrayList<>();
public boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
for (int i = 0; i < characters.size(); i++) {
Object j = characters.get(i);
Matcher matcher = p.matcher((CharSequence) j);
if (matcher.matches()) {
return true;
} else {
System.out.println(
"Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters "););
return false;
}
}
return false;
}
public void setEmail(ArrayList<Character> list) {
characters = list;
}
}
Junit class
#Test
void test() {
String password= "Kd123456";
ArrayList<Character> paswordField=new ArrayList<>();
for(int i= 0 ; i<password.length(); i++){
paswordField.add(password.charAt(i));
}
TestCases valid= new TestCases();
valid.setEmail(paswordField);
assertEquals(true,valid.validatePassword());
}
}
if hope this will help you !!
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class TestCases {
public boolean validatePassword(String s) {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-z0-9 ]).{8,15})",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
return true;
} else {
System.out.println("Please enter a valid password \n"
+ "(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
#Test
public void test() {
String password = "Kd12#3456";
TestCases valid = new TestCases();
assertEquals(true, valid.validatePassword(password));
}
}

How can I get Integer from a string containing numbers,characters?

I was trying to get an int (serial number of a student) from a string looks like "122. Fardinabir 170213" , where "122" is his serial number.
Before this, I tried using nextInt() method with a Scanner of the String, but nextInt() failed to do the job.
Then I have tried this procces...
import java.util.Scanner;
public class tempfile {
public static void main(String[] args) {
int serial_int = 0;
String serial_st;
serial_st = find_serial("122. FardinAbir 170213") ;
System.out.println(serial_st);
serial_int = Integer.parseInt(serial_st);
System.out.println(serial_int);
}
public static String find_serial(String st)
{
String[] parts = st.split(" "); // the first serial part will remain in parts[0]
parts[0].replaceAll("[\\D]", ""); // As I know it will remove non integer and the pure int serial will remain
return parts[0];
}
}
But, replaceAll("[\\D]", "") is not working...
Can anyone please help me to solve this or find a way out to this job...
Thanks in advance...
String line = "122. FardinAbir 170213";
Pattern pattern = Pattern.compile("^(\\d+)");
Matcher matcher = pattern.matcher(line);
if(matcher.find()) {
int id = Integer.parseInt(matcher.group(1));
System.out.println(id);
}
Assuming you also want to get the rest of the string eventually you can use Regex groups
String line = "122. FardinAbir 170213";
Pattern pattern = Pattern.compile("(\\d+)\\.\\s+([^\\s]+)\\s+(\\d+)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("serial: " + matcher.group(1));
int serial = Integer.parseInt(matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
nextInt() probably did not work because scanner expects newline separation
Since you tried using nextInt it seems you just want leading digits, which means you can use the following regex code:
public static String find_serial(String st) {
Matcher m = Pattern.compile("^\\d+").matcher(st);
return (m.find() ? m.group() : null);
}
You could also rely in the serial ending with a period, though that doesn't validate that serial is all digits:
public static String find_serial(String st) {
int idx = st.indexOf('.');
return (idx > 0 ? st.substring(0, idx) : null);
}
This'll do:
public static int getSerialNumber() {
String id = "122. Fardinabir 170213";
int place = 0;
for(int i = 0; i < id.length();i++) {
if(id.charAt(i) == '.') {
place = i;
break;
}
}
return Integer.parseInt(id.substring(0, place));
}
EDIT: you can also do it like this:
public static int getSerialNumber(String name) {
return Integer.parseInt(name.substring(0, name.indexOf('.')));
}
thanks #Andreas for that solution.

Java appending unexpectedly

I'm trying to run a check whether or not a user has entered the #gmail.com suffix to their input. If not, then append it. I'm having a little difficulty because this loop seems to be written correctly to me. I'm at a loss. Anyone? I'm sure it's simple, I just can't see it.
String UN;
Scanner sc = new Scanner(System.in);
String suf = "#gmail.com";
boolean sufd;
// your code goes here
UN = sc.nextLine(); //
if(UN.length() >= 11){
sufd = UN.substring(UN.length()-11,UN.length()-1).equals("#gmail.com");
if(!sufd) {
UN += suf;
}
} else if(UN.length() < 11) {
UN += suf;
}
System.out.print(UN);
Using the official java email package is the easiest:
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
Test Cases:
.

To check is passed string parsable to Integer?

I want to check is a String I pass to Integer.valueOf(String s) a valid String to parse. If one is not parsable I need to return 0.
I do it in the following way:
try{
Integer.valueOf(String s)
} catch(NumberFormatException e) {
return 0;
}
Is it a bad way to do that?
method 1: use a regular expression to check for validity of being a number
public static int parseStrToInt(String str) {
if (str.matches("\\d+")) {
return Integer.parseInt(str);
} else {
return 0;
}
}
method 2: use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric
public static int strToInt(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
if (str.length() == pos.getIndex()) {
return Integer.parseInt(str);
} else {
return 0;
}
}
I would have used:
s = s.trim(); // sometimes user inputs white spaces without knowing it
int value;
if (s.length() == 0) {
value = 0; // obviously not a string
} else {
try{
value = Integer.valueOf(s);
} catch(NumberFormatException e) {
value = 0;
}
}
// do whatever you like here
Hi this will do even the number is double or long, which is useful always while parsing.
List<String> myStrings = new ArrayList<String>();
myStrings.add("text");
myStrings.add("25");
myStrings.add("102.23333333");
myStrings.add("22.34");
NumberFormat nf = NumberFormat.getInstance();
for( String text : myStrings){
try {
System.out.println( nf.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}

Java way to check if a string is palindrome [duplicate]

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}

Categories