Validate if input is not numeric (number) - java

I am just a beginner. Am trying to validate if an input is numeric and not a string. I can't seem to get the correct result. It's always false.
import javax.swing.JOptionPane;
public class CheckDigit
{
public static void main(String[] args)
{
String containsOnlyNumbers;
containsOnlyNumbers = JOptionPane.showInputDialog("Please enter some numbers: ");
// System.out.println(containsOnlyNumbers("12345"));
// System.out.println(containsOnlyNumbers("12abc345"));
if (false)
{
JOptionPane.showMessageDialog(null, "False!");
}
else
{
JOptionPane.showMessageDialog(null, "True!");
}
}
public static boolean containsOnlyNumbers(String str)
{
for (int i = 0; i < str.length(); i++)
{
if (!Character.isDigit(str.charAt(i)))
return false;
}
return true;
}
}
Please advise. TIA.

If your want to use your solution you have to replace
if (false)
with
if (!containsOnlyNumbers(containsOnlyNumbers))
because you are not calling your method (same name for method and String).

You can also try like this,
public static boolean numericCheck(String str)
{
try{
double d=Double.parseDouble(str);
}catch(NumberFormatException e)
{
return false;
}
return true;
}
if method return true then input is a number, if return false input is not numeric

Related

Working with methods

I'm pretty new to coding Java. Below are codes for a program that is supposed to use several methods to ask for a string, reverse the string, test for palindrome and output the result of the test. I'm trying to debug my many errors.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original, String reverse) {
if (original.equals(getString(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String original, Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original,reverse);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
}
return reverse
}
public static void main(String[] args) {
System.out.print(promptForPalindrome);
}
}
For a start in main
you are calling
System.out.print(promptForPalindrome);
but if you look at the method promptForPalindrome you will see that it takes the parameters String original, Scanner Keyboard
BUT
These parameters are not even used, so maybe just delete them and change the main code to be
System.out.print(promptForPalindrome ());
Consider reading a basic java tutorial as well.
edit
Similar problems exist for isPalindrome - I suggest you change to
public static boolean isPalindrome(String original) {
return original.equals(getReverse(original));
}
and call it in as
boolean answer = isPalindrome(original);
But then your answer in
while (answer == false) {
will never change - so many bugs
The method signatures for the isPalindrome needs to be changed to only accept 1 string argument because you don't have the reversed string when it is called. Also there is no reason to pass in a scanner object for the prompt method because you instantiate it in the method. Also I changed your .equals to .equalsIgnoreCase so you don't get messed up by capitals. Also you need to update your boolean after each loop.
public static String getReverse(String Original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equalsIgnoreCase(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = keyboard.nextLine();
boolean answer = isPalindrome(original);
while (answer == false) {
System.out.printf("Error: %s is not a palindrome. Please enter a palindrome.", original);
original = keyboard.nextLine();
answer = isPalindrome(original);
}
return getReverse(original);
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
Hope this helps I may have made some typos so let me know.
Your code has lot of errors. Check the below working code with comments in it.
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length() - 1; i > -1; i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) { // Two args are not required
// use equals if you need a case sensitive match
if (original.equalsIgnoreCase(getReverse(original))) { // Call getReverse() to reverse the string
return true;
} else {
return false;
}
}
public static String promptForPalindrome() { // Arguments are not required
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a palindrome:");
String original = null;
boolean answer = false;
do { // Use a do-while loop since you need to continue till it is success
original = keyboard.nextLine();
answer = isPalindrome(original);
if (!answer) {
System.out
.printf("Error: %s is not a palindrome. Please enter a palindrome.",
original);
}
} while (!answer);
keyboard.close(); // Close the Scanner
return original;
}
public static void main(String[] args) {
System.out.print(promptForPalindrome());
}
Thanks guys for all your help,
I was finally able to debug the code.
package osu.cse1223;
import java.util.Scanner;
public class Homework08a {
public static String getReverse(String original) {
String reverse = "";
for (int i = original.length()-1; i>-1;i--) {
reverse = reverse + original.charAt(i);
}
return reverse;
}
public static boolean isPalindrome(String original) {
if (original.equals(getReverse(original))) {
return true;
}
else {
return false;
}
}
public static String promptForPalindrome(String msg, Scanner keyboard) {
System.out.print(msg);
String userInput = keyboard.nextLine();
return userInput;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String msg ="Please enter a Palindrome";
String userInput = promptForPalindrome(msg, keyboard);
while (isPalindrome(userInput) == false) {
userInput = promptForPalindrome(msg, keyboard);
}
System.out.printf("%s is a palindrome", userInput);
}
}

Recursive method return values in asterisks

I'm trying to create a recursive method that returns a value, and prints the value in my main method. I'm confused on how to return and print in main() a row of X asterisks (**..)
X being a integer on the commandline.
For example the commandline argument is 5.
It should output to: *****
My code so far:
public static void main(String[] commandlineArguments){
if(commandlineArguments.length == 0){
System.out.println("Please enter a least one commandline!");
}
else{
Integer number = new Integer(0); //initialize number
try{
Integer x = Integer.parseInt(commandlineArguments[0]);
}
catch(NumberFormatException exception){ //NumberFormatException
System.out.println(exception+" is not a integer!");
System.exit(1); //end program
}
Integer num1 = recursiveMethods.asterisks(number); //A (return address)
System.out.println(num1);
}
}
public static Integer asterisks(Integer number){
String asterisks1 = "*";
for(int i = 0; i < number; i++){
return i;
}
return number;
}
}
A recursive method have two characteristics:
It calls to itself to provide the solution
It has a base case that contains where the recursive call must stop.
Your asterisks method does not fulfill any of these. Since this looks like homework, I would only provide an explanation about how this method should be, the implementation will be yours:
Since your method needs to return asterisks, it would be better returning a String instead of an Integer. This String will contain all the *s needed.
Define a base case. This can be where number have a value of 1.
If number is greater than 1, then you should return an asterisk and the result of calling to asterisks method using the rest of asterisks the whole result needs.
The problem is here:
for(int i = 0; i < number; i++){
return i;
}
This loop will only run one time, and it will immediately return i = 0. You don't want that. Make it append a * to your asterisks1 variable each iteration, then after the loop is finished, return asterisks1 to the caller and print it.
Also, just FYI, this method is not recursive. A recursive method by definition calls itself at some point.
You probably want to call the asterisk function recursively, and return the built up String of asterisks, something like this:
public static void main(String[] commandlineArguments) {
if (commandlineArguments.length == 0) {
System.out.println("Please enter a least one commandline!");
} else {
Integer number = new Integer(0); // initialize number
try {
number = Integer.parseInt(commandlineArguments[0]);
} catch (NumberFormatException exception) { // NumberFormatException
System.out.println(exception + " is not a integer!");
System.exit(1); // end program
}
String asterisk = asterisks(number); // A (return address)
System.out.println(asterisk);
}
}
public static String asterisks(Integer number) {
if (number == 0) {
return "";
} else {
return "*" + asterisks(number - 1);
}
}
to do it recursively you must call itself in itself. for example :
public static void main(String[] commandlineArguments){
if(commandlineArguments.length == 0){
System.out.println("Please enter a least one commandline!");
}
else{
Integer number = new Integer(0); //initialize number
try{
Integer x = Integer.parseInt(commandlineArguments[0]);
}
catch(NumberFormatException exception){ //NumberFormatException
System.out.println(exception+" is not a integer!");
System.exit(1); //end program
}
recursiveMethods.asterisks(number); //A (return address)
}
}
public static void asterisks(Integer number) {
if(number == 0)
return;
else {
System.out.print("*");
asterisks(number - 1);
}
}
}
Can be done as,
public static String asterisks(int n){
return (n==1)?"*":asterisks(n-1)+"*";
}
Note : return Type is String
EDIT: For n <= 0 it prints nothing
public static String asterisks(int n){
return (n<=0)?"":asterisks(n-1)+"*";
}

Determining type of data contained in a String

This is an extension to below question in StackOverflow as I am not understanding the accepted answer.
How do you determine the type of data contained in a string?
If someone could please give a sample code for below case:
I have a String array as below:
String[] myArray = new String[4];
myArray[0] = "one";
myArray[1] = "2012-02-25";
myArray[2] = "12345.58";
myArray[3] = "1245";
I want something as below:
for(String s:myArray){
if(s is a number){
System.out.println("A number!");
}
else if(s is a float){
System.out.println("A float!");
}
else if(s is a date){
System.out.println("A date!");
}
else if(s is a text){
System.out.println("A text!");
}
}
But I don't know what will come inside the IF conditions to determine the type of data in given String.
Thanks for reading!
The simplest way to do it is to create the aformentioned methods an simply try to parse the string like (but you have to remember that you cannot tell 100% what datatype a certain pattern is, can be multiple times at once):
public static boolean isANumber(String s) {
try {
BigDecimal d = new BigDecimal(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isAFloat(String s) {
//same as number, unless you want is a number to
//check if it an integer or not
try {
BigDecimal d = new BigDecimal(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isADate(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
sdf.parse(s);
return true;
} catch (Exception e) {
return false;
}
}
public static boolean isAText(String s) {
//everything could be considered a text
// unless you want to check that characters are within some ranges
return true;
}
public static void main(String[] args) {
String[] myArray = new String[4];
myArray[0] = "one";
myArray[1] = "2012-02-25";
myArray[2] = "12345.58";
myArray[3] = "1245";
for(String str : myArray){
if(str.matches("[\\d]+")){
System.out.println(str + " is integer");
}
else if(str.matches("[\\D]+")){
System.out.println(str + " is word");
}
else if(str.matches("[\\d.]+")){
System.out.println(str + " is double");
}
else if(str.matches("\\d{4}-\\d{2}-\\d{2}")){
System.out.println(str + " is date");
}
}
}
Output:
one is word
2012-02-25 is date
12345.58 is double
1245 is integer
One way to do it is by trying to parse the string.
Here is an example for one of the types;:
boolean isFloat(String x) {
try {
Float.parseFloat(x);
} catch (Throwable e) {
return false;
}
return true;
}
Note:
As an integer can be parsed a a float you need to test if it is an integer first.
So:
if (isInteger(s)) {
// Integer
else if (isFloat(s)) {
...
for(String s:myArray){
if(NumberUtils.isNumber(s)){ //From Apache commons
double d= Double.valueOf(s);
if (d==(int)d){
System.out.println("A number!");
}else{
System.out.println("A Float!");
}
}else if(isValidDate(s)){
System.out.println("A date!");
}else{
System.out.println("A text!");
}
}
Method for valid date check
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
Write function like :
private boolean isFloat(String str) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException) {
return false;
}
}
And check the type. Or you can just use apache commons NumberUtils
There's no way of defining an array of strings with a declaration of a specific datatype. If you need something like that, use collection like List, e.g. a list of date objects. For strings, you have to programatically determine it by analyzing the data or if you already know what type of data an array of strings or a string contains in your program since you are the one who wrote it, then handle accordingly.
You can create a custom object/class which can take the value and type of data that value represents.

null pointer exception prob in my coding

I am always getting nullPointerException on line validateCarPlate(nStr) in the main method and on line if(y.matches(rex)). How should i edit to remove the nullPointerException?
import javax.swing.*;
import java.lang.Exception;
public class Q2{
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y.matches(rex)){
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
arr[i] = x.charAt(i);
}
Looks like
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
this returns null
change the code like this
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
if(nStr != null)
{
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
}
Since, javadocs for JOptionPane#showInputDialog() says Shows a question-message dialog requesting input from the user I think you forgot to give a input.
change you method like that
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y == null){
// put some message to handle that exception such as
// JOptionPane.showMessageDialog(null,"Some Message");
}else if(y.matches(rex))
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
Also put the code of computeCheckDigit(y); method.
If you click the Cancel button, JOptionPane.showInputDialog will return a null. You can check the return value before passing nStr to validateCarPlate. If a null returned, just drop this nStr and continue the loop (or break it according to your requirement).

Allowing a maximum number of times for system to accept incorrect PIN

I made a java login screen for a console application, but I need it to allow the user to input ther wrong PIN only 3 times. After the user has entered the PIN more than 3 times, the system should exit.
However, the loop which I used for the else part of the if condition does not seem to be making any changes to the program. (program wont execute the else part even once). Does anybody know what I am doing wrong?
if (userPIN.equals(a[0]))
{
System.out.println("You have login!");
valid=true;
String b=a[2];
Login.c=Double.parseDouble(b);
System.out.println(c);
obj.balance = Login.c;
obj.MainMenu();
System.exit(0);
}
else if(userPIN != a[0])
{
int count=0;
for(int i=0;i<count;i++)
{
System.out.println("Invalid PIN!");
check();
}
}
int count=0;
for(int i=0;i<count;i++)
The for loop's condition is initially false, hence it will never execute its body.
You have many problems in your code :
in the first if your using :
userPIN.equals(a[0])
but in the else you're using :
userPIN != a[0]
Your for loop cannot run correctly :
int count=0;
for(int i=0;i<count;i++)
Here is the correct implementation using Object-Orientation :
import java.util.Scanner;
public class PinChecker {
// Immutable Class
private static final class Pin {
private String _pin;
Pin(String pin) {
this._pin = pin;
}
public String toString() {
return _pin;
}
public boolean equals(Pin pin) {
if(pin.toString().equals(_pin)) {
return(true);
} else {
return(false);
}
}
}
public static final int NB_OF_TRIES = 3;
public static void main(String[] args) {
System.out.println("Enter your PIN :");
Pin userPin = new Pin("FOO");
Scanner console = new Scanner(System.in);
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
Pin keyedPin = new Pin(console.nextLine());
i++;
if(userPin.equals(keyedPin)) {
pinMatch = true;
} else {
System.out.println("Invalid PIN!");
}
}
if(pinMatch) {
System.out.println("OK, nb of tries :" + i);
} else {
System.out.println("KO, nb of tries :" + i);
}
}
}
You can store the keyedPin object if you need to.
in the else part try !(userPIN.equals(a[0]))
Your else part is not checking the contents.

Categories

Resources