[RESOLVED!] Problem with code recognizing invalid characters after spaces....
Hello. I have to write a program that has the user enter a number. As long as the number is a whole number, it is valid. If not, it returns an error message. Well everything works fine if there are no spaces. But if the user types spaces and it has the letter "g" in something after the space, it will return it as valid. This is what I have. Is there any code to either 1) crash the program and return the error message if user enters a space or 2) compare ALL the characters in the user input? Thanks in advance!
Code Java:
import java.util.Scanner;
public class CardNumberValidation {
/**
* @param args
* @return
*/
public static void main(String[] args) {
Scanner QWERTY = new Scanner(System.in);
System.out.println("Enter the 16 digit number located on" +
" the front of your card.");
{ try
{
long s = 0;
s = QWERTY.nextLong();
System.out.println("Card number entered is valid!");}
catch(Exception e)
{
System.err.println("NOT A VALID CARD NUMBER. Please try again.");
}
}
}
}
Re: Problem with code recognizing invalid characters after spaces....
Can you post the console from when you execute the code that shows what is typed in?
I get a java.util.InputMismatchException when I enter a g.
Also print out the value of s to show what value was read.
Re: Problem with code recognizing invalid characters after spaces....
try changing your catch parameter to (NumberFormatException e) and see what happens
Re: Problem with code recognizing invalid characters after spaces....
Changing the exception class to a more restricted one won't change the code catching an exception. The more general class will catch all the exceptions.
If the OP is entering is a number followed by space(s) followed by some more stuff.
The nextLong() method reads and converts the number and leaves the rest (after the space(s)) in Scanner's buffer.
If the code printed out the value of s the OP would see what is happening.
Re: Problem with code recognizing invalid characters after spaces....
OH I GOT IT! I put the user input into a String using the nextLine command then parsed it. That way it takes that entire line as the input, not just up until a space. Works like a charm now!
Code Java:
import java.util.Scanner;
public class CardDigitValidation {
/**
* @param args
* @return
*/
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the 16 digit number located on" +
" the front of your card. NO SPACES PLEASE!");
try
{
String s;
s = userInput.nextLine();
Long.parseLong(s);
System.out.println("Card number entered is valid!");
}
catch(Exception e)
{
System.err.println("NOT A VALID CARD NUMBER. Please try again.");
}
}
}