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");
}
}
}
Related
I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:
We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.
So far I only have a basic input/output prompt
//variables
String myID;
//inputs
System.out.println("Enter your ID:");
myID = input.nextLine();
So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.
As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered
import java.util.Scanner;
class LinearArray{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;
do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}
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();
}
I am trying to validate user input using a regular expression in a while loop. I am trying to accept only one lower-case word (letters a-z inclusive).
public class testRedex{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Please enter a key: ");
while(!console.hasNext("[a-z]+")){
System.out.println("Invalid key");
console.next();
}
String test = console.next();
System.out.println(test);
}
}
My question is, is there any difference between having the regular expression as "[a-z]+" and "[a-z]+$"? I know that $ will look for a character between a-z at the end of the string, but in this case would it matter?
Yes there is a difference, if you'll use: ^[a-z]+$ it means that whatever the user inputs should be combined only from [a-z]+.
If you don't add the ^ and the $ the user could insert other characters, space for example, and there will still be a match (the first part of the string until the space.
Let's see an example:
run your code with the input: "try this" (it'll print "try")
now change the regex to ^[a-z]+$ and run with the same input (it'll print "Invalid key").
The way I would re-write it is:
System.out.print("Please enter a key: ");
String test = console.nextLine();
while (!test.matches("^[a-z]+$")) {
System.out.println("Invalid key");
test = console.nextLine();
}
System.out.println(test);
The difference are as follows
[a-z]+ means a,b,c,...,or z occurs more than one time
[a-z]+$ means a,b,c,...,or z occurs more that one time and must match end of the line
Yet at the end, they give you the same result.
if you want to understand it better try this
([A-Z])([a-z]+$)
It start with a capital letter and end with more than one time small letter
output:
Please enter a key: AAAAaaaa
Invalid key
Aaaaaa
Aaaaaa
Another way you can get the expected result from what you are looking for
code:
int i = 0;
String result = "";
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter your key:");
if(input.hasNext("^[a-z]+$")){
result = input.next();
i=1;
}else{
System.out.println("Invalid key");
}
}while(i==0);
System.out.println("the result is " + result);
output:
Enter your key:
HHHh
Invalid key
Enter your key:
Hellllo
Invalid key
Enter your key:
hello
the result is hello
So this is my code i dont know what to add if i want to display invalid message for the non numeric inputs please help ty
import java.util.Scanner;
public class Date
{
public static void main (String args [])
{
int x;
Scanner in = new Scanner (System.in);
System.out.print("Enter a date ");
x = in.nextInt();
while (x < 1520 || x > 3999)
{
System.out.println ("Invalid Gregorian Calendar date.");
System.out.print ("Please Input a valid Gregorian Calendar date: ");
x = in.nextInt();
}
System.out.println("Good");
Use a try catch block, and put x = in.nextInt(); inside it
I've changed your code a bit. I think this is what you were aiming for.
I'm not that good in explaining but I try to tell what I did.
First of all I got rid of your in.nextInt() since this is very restrictive. It does only accept an integer and will throw an exception if you type something else in. Normally this would be OK, but since you want the user to be able to correct the input, this will cause more troubles than it would solve.
I then put your code into an infinite loop while(true) which assures, you do not have to restart your application again once you've typed in a wrong value.
What is going on within the loop is quite simple. The console prints out what you want the user to do and reads the consoles input as a String, so you don't have to face any exceptions in the first place.
I then try to parse the given String into an integer value. I added trim() to kill leading spaces as well as trailing, so I won't have to deal with users being confused by typing in numbers with a space since they don't directly see whats wrong when getting their "not an integer" error. This would be thrown, if the input contains spaces.
Now I check whether or not the given integer-value fits your specifiation. I don't need a loop here, so I changed it to be a simple if-statement.
If the value is wrong (or lets say the if (x < 1520 || x > 3999) returns true) I'm going to print out your error message. Since we already passed casting the String input into the integer and we do not reach the else-branch we now return back to the beginning of our loop with printing out the request again before waiting for a new input to be made.
Now, as soon as the user typed in another value, e.g. 2011 (which is valid based on your specification) we will now reach the else-branch which prints the "Good" and leaves the loop by calling break. And since there is nothing left to do for the application it will stop running. If you want the user to be able to type in new values in the positive case, you simply have to remove the break-statement.
If the user types in a value which is not an integer, the cast will fail and throw a NumberFormatException. We catch this exception by surrounding the cast with the try-catch-block and print out the integer-error once we've reached the catch-block.
Then the application reacts the same way like if you typed in a wrong number and we will return to the beginning of the loop again.
The reason for putting a try-block around the Scanner is to handle closing.
import java.util.Scanner;
public class Date {
public static void main(String args[]) {
String input = "";
int x = 0;
try (Scanner in = new Scanner(System.in);) {
while (true) {
System.out.print("Please Input a valid Gregorian Calendar date: ");
input = in.nextLine();
try {
x = Integer.parseInt(input.trim());
if (x < 1520 || x > 3999) {
System.out.println("Invalid Gregorian Calendar date.");
}
else {
System.out.println("Good");
break;
}
} catch (NumberFormatException e) {
System.out.println("Given value \"" + input.trim() + "\" is not an integer.");
}
}
}
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int x;
if(in.hasNextInt()){
x = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a number");
}
To keep prompting until a valid number is entered
int x;
System.out.println("Enter a number: ");
while(!in.hasNextInt()){
System.out.println("Invalid number, try again: ");
key.nextLine(); // Flush out invalid number
}
x = key.nextInt();
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.