Home > Enterprise >  I want to print a error message if a String variable contains numbers
I want to print a error message if a String variable contains numbers

Time:11-22

I am doing a exercise where i need to accept numbers in a string variable and divide them with 10, and i am not allowed to use .nextInt(); or Integer.ParseInt(); I want to print out an error message if a String variable contain letters. Right now the error message works if i only enter letters in the string variable but if i mix it up with letters and numbers the error message does not work. What can i do to solve this problem.

Code so far:

import java.util.regex.*;

import java.util.Scanner;

public class Exercise8 {

private static Scanner input;

public static void main(String[] args) {

    System.out.println("Enter some numbers");
    
    input = new Scanner(System.in);
    double divide = 10;
    int sum = 0;
    int x = 0;
    int j = 0;
    
    while (x < 1) {
        
        String strNumbers = input.next();
        
        if (!Pattern.matches("[a-zA-Z] ", strNumbers)) {
            
              x;

            for (int i = strNumbers.length() - 1; i >= 0; i--) {
                
                sum  = Math.pow(10, j) * (strNumbers.charAt(i) - '0');
                j  ;    
            }   
            
            System.out.println("Your numbers: "   sum);
            System.out.println("Your numbers divided by 10: "   sum/divide);
        }
        
        else {
            
            System.out.println("Invalid");
        }
    }
}

}

CodePudding user response:

You can invert if statement and check whether strNumbers variable contains ONLY digits.

if (Pattern.matches("\\d ", strNumbers)) {
    //handle case where number is valid ...
}
else {
    System.out.println("Invalid");
}
  • Related