Restrict user to input only numbers(int, float, double) - java

A user has to input only numbers(int, float, double) into an ArrayList. If a user inputs anything but numbers, an exception InputMismatchException must be thrown.
I thought of using Number class.
Scanner input = new Scanner(System.in);
ArrayList<Number> number = new ArrayList<Number>();
System.out.println("Enter number");
(data_type???) number_var = input.??????;
number.add(number_var);
This code will be in do while asking user if he/she wants to continue to give input or not. The only problem is how to restrict user to give input as only numbers. This should be done without creating another class but a method is allowed to restrict user.

You could just accept all numbers as doubles. Ints and floats could be converted to doulbles seemlesly:
Scanner input = new Scanner(System.in);
List<Double> number = new ArrayList<Double>();
System.out.println("Enter number");
number.add(input.nextDouble());

The docs for Scanner should describe what you need. Your scanner can read input as any kind of number that you want. If the input doesn't match what you are expecting it will throw the InputMismatchException.

Related

Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?

I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.

Using user input from a scanner multiple times?

I am trying to use a user-entered number from the scanner in my code in multiple places. Below the line should be the same user-entered number as the first. Is this possible?
Scanner inputHere = new Scanner(system.in);
System.out.println("Please select me");
String inputHereOne = inputHere.nextLine();
System.out.println("----------------------------------");
Yes, it's possible. Use the value stored in inputHereOne. No need to call inputHere.nextLine() until you actually need the next line of input. Like so:
System.out.println(inputHereOne);
System.out.println(inputHereOne);
This will print inputHereOne, twice.

How to avoid a runtime error where a string is inputted into a .nextInt();?

How to avoid a runtime error where a string is inputted into a .nextInt();?
I'm trying to do user input. Say they were to enter a letter by accident where a number is required, it will just show a runtime error. How do I make it so more inputs pop up until a number is inputted?
Scanner userInput = new Scanner(System.in);
int num1;
System.out.println("Please enter an interger number:);
num1 = userInput.nextInt();
When the box pops up for the user to enter an interger they input a string and get a runtime error. How do I avoid this error?
An input that would create this error would be any letter.
I am using DrJava on Eclipse.
Use the hasNextInt() method, so something like
if (userInput.hasNextInt()){ //do Something.. }
Or take any input as a string, then parse that as an Integer, and do a try catch to find errors.

How do i declare and read values into integer values?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Read an input of trillions value?

I want to know how to read a number from 1 to trillions in My Java application without an error.
This is the part of my code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
long value = sc.nextInt();
System.out.print("Your money in String : "+value);
If I enter a value from about 1 to 2.111.111.999 it works fine but
every time I run it and enter greater than that, there's this error message :
Exception in thread "main" java.util.InputMismatchException: For input string: "1000000000000"
at java.util.Scanner.nextInt(Scanner.java:2097)
at java.util.Scanner.nextInt(Scanner.java:2050)
at konversiangka.Konversiangka.main(Konversiangka.java:28)
Java Result: 1
I guess this is a "data type" mistake.
I know if you want to store a trillion in a long data type you have to add "L" in the end
of the value, like this, "1000000000000L". But I don't want User to add that when they enter a value on the program,
So can you help Me how to do that?
I Appreciate any suggestion and correction, thanks.
Use
long value = sc.nextLong();
instead.
The reason for the error is that the maximum value that can be put into an int is 2,147,483,647, and even though you declared the variable as a long, Scanner.nextInt() always tries to convert the number into an int.
You can use a long as Tharwen mentioned or you can use java.math.BigDecimal. BigDecimal is a class made for holding a decimal number as big (or small) as you want. You can see all the primitive data types and their max/min size here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
BigDecimal value = sc.nextBigDecimal();
System.out.print("Your money in String : "+value);
Output:
Enter your money value : 271075217301782039710237102710521231.23
Your money in String : 271075217301782039710237102710521231.23

Categories