This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 8 years ago.
I am a student and i have a little problem with validation inputs.
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
//If name contain other than alphabetical character print an error
double number;
System.out.println("Enter number:");
name = keyboard.nextDouble();
//If number contain other than number print an error
What i have tried is test to parse the string to double but i could not.
I have no idea how to test if the double is only number.
Please give me a clue of what i should do.
You can use Regular expression to check if the input match your constraint as follow :
String name;
System.out.println("Enter name:");
name = keyboard.nextLine();
if (!name.matches("[a-zA-Z_]+")) {
System.out.println("Invalid name");
}
String number;
System.out.println("Enter number:");
number = keyboard.nextLine();
if (!number.matches("[0-9]+")) {
System.out.println("Invalid number");
}
Here is a good tutorial to learn regex .
You can loop through each character of the String and check if it's not alphabetic using Character.isAlphabetic(char):
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name:");
String name = keyboard.nextLine();
for (char c : name.toCharArray()) {
if (!Character.isAlphabetic(c)){
System.out.println("INVALID");
break;
}
}
To only accept numbers, you can do something similar using the Character.isDigit(char) function, but note that you will have to read the input as a String not a double, or get the input as a double and the converting it to String using Double.toString(d).
double number = 0;
try {
number = Double.parseDouble(name)
} catch (NumberFormatException ex) {
System.out.println("Name is not a double.");
}
If number is not a double, you can catch a NumberFormatException.
It seems you are using scanner. If you are, you can use the Scanner class' hasNextDouble() to check if the input is a double before reading the double as shown below:
double number;
System.out.println("Enter number:");
if (keyboard.hasNextDouble()){
name = keyboard.nextDouble();
}
Have a look at the Scanner class docs for more information.
There is also the "fancier" regex solution.
Java Pattern Documentation
You can use this (untested code) given you used nextLine() for reading BOTH inputs:
boolean isWordOnly = Pattern.matches("\w*", name); //name is in your code
boolean isFloatOnly = Pattern.matches("\d*.?\d*", number); //number is in your code too
Now the too boolean values tell you if there is the desired format in your input. You can add it in a do - while loop or anything you want.
It is a good idea to start studying reg(ular) ex(presions) because they are useful in string formatting (Imagine that you have to test if the input is a valid email...). Also used to check for SQL injections and many key things in apps and programs generally.
Related
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I was writing a code for a program in which the user enters 2 to 4 numbers which can be up to 2 decimal places long. However before the user enters these numbers they must enter the pound symbol, e.g. #12.34. I was wondering how i would check if the double value entered began with the pound sign, and if the user forgot to input it, to re-prompt them to do it again. So far im using a String value and the '.startsWith()' code, but I'm finding later on that a String value is making the rest of the program impossible to code, so i was wanting to keep it a double value. This is the code I have at the moment but wish to change to a double:
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
I was wanting to replace the String with double as mentioned previously.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
// if your excution reaches here. then it means the values entered by user is starting from '#'.
String temp = input;
double value = Double.parseDouble(temp.replace("#",""));
For the rest of the program use value. I think the coding should be possible now.
A double value doesn't have a currency symbol. You should check for the currency symbol as you are doing and remove it before parsing the double.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("£")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
doulble number = Double.parseDouble(input.substring(1));
You should use the startsWith method. I don't know why you say that
I'm finding later on that a String value is making the rest of the program impossible to code
Basically, you want to prompt it repeatedly until the user enters the # sign. So why not use a while loop?
System.out.println("Enter a number:");
String s = keyboard.next();
double d = 0.0; // You actually wnat to store the user input in a
// variable, right?
while (!s.trim().startWith("#")) {
System.out.println("You did not enter the number in the correct format. Try again.");
s = keyboard.next();
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
}
That's a lot of code!
Explanation:
First, it prompts the user to enter a number and store the input in s. That's easy to understand. Now here comes the hard part. We want to loop until the user enters the input with the correct format. Let's see what kind of invalid inputs are there:
The user does not enter a # sign
The user does not enter a number
The first one is handled by the startsWith method. If the input does not start with #, ask the user again. Before that, trim is first called to trim off whitespace in the input so that input like " #5.90" are valid. The second is handled by this part:
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
If the input is in a wrong format, ask the user again. If the user enters a string with a length less than 1, ask the user again.
"But wait! Why is there a call to the substring method?" you asked. If the user does enter a # in the front, followed by a correct number format, how would you convert that string to a double? Here I just kind of trim the first character off by calling substring.
You could try something like this which removes all character that's not a number or a point:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("Input a number: ");
while (!(input = br.readLine()).equals("quit")) {
Double parsedDouble;
if (input.matches("#[0-9]+\\.[0-9]{1,2}")) {
parsedDouble = Double.parseDouble(input.replaceAll("[^0-9.]+", ""));
System.out.println("double: " + parsedDouble);
System.out.println("Input another number: ");
} else {
System.out.println("Invalid. Try again. Example: #10.10");
}
}
}
I'm trying to only accept numbers from a user. This code works for giving them an error message if they enter a letter. But it doesn't work for if they hit Enter or just white space. I've tried initializing a String called test as null and then setting scnr.nextLine() = test, and then checking if test is empty, but I didn't understand how to keep the rest of the program operating correctly when I did that. Scanner is very tricky to me. Please help!
double mainNumber = 0;
System.out.print("Enter a number: ");
if (scnr.hasNextDouble() ){
mainNumber = scnr.nextDouble();
System.out.println(mainNumber);
scnr.nextLine();
}
else {
System.out.println("Sorry, please enter a number.\n");
scnr.nextLine();
}
You have to use while-cycle and loop input as long as needed before user put a valid number.
This code
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double mainNumber = 0;
boolean isValidNumber = false;
System.out.print("Enter a number: ");
while (isValidNumber == false) {
String line = scnr.nextLine();
try {
mainNumber = Double.valueOf(line);
isValidNumber = true;
} catch (NumberFormatException e){
System.out.print("Sorry, please enter a number.\n");
}
}
System.out.println("Main number is: " + mainNumber);
}
Having this sample output :
Enter a number: sdfgsgxb
Sorry, please enter a number.
xcvbxcvb
Sorry, please enter a number.
gsfdfgsdf
Sorry, please enter a number.
aearg
Sorry, please enter a number.
15.77
Main number is: 15.77
Well I guess your code is in a while loop or something ? So that it keep asking until the user enter the right value.
Then you should (for convenience) use String str = scnr.nextString() instead of nextDouble() and analyze the string it returned.
You can use str.trim() to remove whitespaces (and then check if string is empty with str.isEmpty() ), and to check if it's a number you can use regexp ( How to check that a string is parseable to a double? and any regex tutorial you can find ) or just use this regex: str.matches("\\d+") (returns true if str is a number, but no comma here).
Of course, don't forget to cast your String as double after: Double.parseDouble( str.replace(",",".") );. I hope the "replace" part is obvious ;)
You might use the following snippet to read one double value:
Scanner scanner = new Scanner(System.in);
try {
double number = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}