Java util inputmismatchexception scanner nextfloat

What is InputMisMatchException in Java how do we handle it?

From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.

To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().

Whenever you take inputs from the user using a Scanner class. If the inputs passed doesn’t match the method or an InputMisMatchException is thrown. For example, if you reading an integer data using the nextInt() method and the value passed in a String then, an exception occurs.

Example

import java.util.Scanner; public class StudentData < int age; String name; public StudentData(String name, int age)< this.age = age; this.name = name; >public void display() < System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); >public static void main (String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); StudentData obj = new StudentData(name, age); obj.display(); >>

Runtime exception

Enter your name: Krishna Enter your age: twenty Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at july_set3.StudentData.main(StudentData.java:20)

Handling input mismatch exception

The only way to handle this exception is to make sure that you enter proper values while passing inputs. It is suggested to specify required values with complete details while reading data from user using scanner class.

Читайте также:  Css align div contents to center

Источник

Why am I getting InputMismatchException?

docs.oracle.com/javase/1.5.0/docs/api/java/util/… Look at this. Maybe the scanner was not able to parse what you entered into the console? For example, it asked for a number, you entered «hello»?

Remove Scanner reader = new Scanner(System.in); from the askForMarks(); Everything works for me then.

5 Answers 5

Instead of using a dot, like: 1.2, try to input like this: 1,2.

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try < // . >catch (InputMismatchException e) < System.out.print(e.getMessage()); //try to find out specific reason. >

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

You have entered something, which is out of range as I have mentioned above.

I’m really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*; public class Test < public static void main(String. args) < new Test().askForMarks(5); >public void askForMarks(int student) < double marks[] = new double[student]; int index = 0; Scanner reader = new Scanner(System.in); while (index < student) < System.out.print("Please enter a mark (0..30): "); marks[index] = (double) checkValueWithin(0, 30); index++; >> public double checkValueWithin(int min, int max) < double num; Scanner reader = new Scanner(System.in); num = reader.nextDouble(); while (num < min || num >max) < System.out.print("Invalid. Re-enter number: "); num = reader.nextDouble(); >return num; > > 

As you said, you have tried to enter 1.0 , 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7 , press enter and then enter second number (e.g. 6.7 ).

Источник

Why is scan.nextFloat() not reading only float values?

I trying to read ONLY float value from a file that consists of integer and float values however when I do scan.nextFloat() it still reads the next integer value and converts it into floats and adds it to my list of points. Below is what I am doing.

Sample points in a file 3 4 3.3 4 5 2.3 3 3 Is there a way to just read the float values from the file such as 3.3 and 2.3. Also shouldn’t scan.nextFloat() read only float values while skipping the int values?

«shouldn’t scan.nextFloat() read only float values while skipping the int values» — a Scanner skips only when explicitly told to, it doesn’t magically decide what you meant to skip. Also, a number without a decimal point is a valid float. If you want to ignore the integers you’ll have to code explicitly to ignore them.

2 Answers 2

You pretty much have to accept that nextFloat is going to read a number like 3 as 3.0. If you don’t want numbers that are whole integers, then just filter them out after you’ve read them. (See the other answers.) But if you want to include «3.0» but not «3» then you will have to read the values in as strings and only parse the ones that have decimals:

According to docs the hasNextFloat() method:

Returns true if the next token in this scanner’s input can be interpreted as a float value using the nextFloat() method

nextFloat() states that (emphasis mine):

(. ) If the next token matches the Float regular expression defined above then the token is converted into a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Float.parseFloat. If the token matches the localized NaN or infinity strings, then either «Nan» or «Infinity» is passed to Float.parseFloat as appropriate.

Float, on the other hand could be a Decimal, HexFloat or SignedNonNumber. Decimal could be a DecimalNumeral, which could be a Numeral, which is a Digit.

Another way of taking only the float values is this (if your file contains only integers and floats of course):

while(scan.hasNext() && !scan.hasNextInt()) < points.add(scan.nextFloat()); 

Источник

I can't get a input from user as float in java [duplicate]

If you want to have any whitespace character as a seperator just use next() for reading a String :

// Input int a = in.nextInt(); // Integer String b = in.next(); // String float c = in.nextFloat(); // float 

This will accept all input values in one line or with line breaks

123 abc 456.789 Given integer :123 Given string :abc Given Float :456.789 
123 abc 456.789 Given integer :123 Given string :abc Given Float :456.789 

If you aim to have only line breaks as input separator use the solution suggested by @marc:

// Input int a = in.nextInt(); // Integer in.nextLine(); String b = in.nextLine(); // String float c = in.nextFloat(); // float 
123 abc 456.789 Given integer :123 Given string :abc Given Float :456.789 

and consequent expressions in the same line will be ignored:

123 abc 4.5 def 6.7 Given integer :123 Given string :def Given Float :6.7 

nextInt() does not read the new line character (when you click return). You need an additional nextLine() Try with:

int a = in.nextInt(); // Integer in.nextLine(); String b = in.nextLine(); // String Float c = in.nextFloat(); // Float 

Advances this scanner past the current line and returns the inputthat was skipped.This >method returns the rest of the current line, excluding any lineseparator at the end. The >position is set to the beginning of the nextline. Since this method continues to search through the input lookingfor a line separator, it >may buffer all of the input searching forthe line to skip if no line separators are >present.

Advancing the line causes that in.nextFloat tries to read and parse "stack". This will become visible if you write only numbers in the console

i recommend to read strings with next() instead of nextLine()

Источник

Java.util.Scanner.nextFloat() Method

The java.util.Scanner.nextFloat() method scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.

Declaration

Following is the declaration for java.util.Scanner.nextFloat() method

Parameters

Return Value

This method returns the float scanned from the input

Exception

  • InputMismatchException − if the next token does not match the Float regular expression, or is out of range
  • NoSuchElementException − if the input is exhausted
  • IllegalStateException − if this scanner is closed

Example

The following example shows the usage of java.util.Scanner.nextFloat() method.

package com.tutorialspoint; import java.util.*; public class ScannerDemo < public static void main(String[] args) < String s = "Hello World! 3 + 3.0 = 6.0 true "; Float f = 1.2385f; s = s + f; // create a new scanner with the specified String Object Scanner scanner = new Scanner(s); // use US locale to be able to identify floats in the string scanner.useLocale(Locale.US); // find the next float token and print it // loop for the whole scanner while (scanner.hasNext()) < scanner.next(); // if the next is a float, print found and the float if (scanner.hasNextFloat()) < System.out.println("Found :" + scanner.nextFloat()); >> // close the scanner scanner.close(); > >

Let us compile and run the above program, this will produce the following result −

Found :3.0 Found :3.0 Found :6.0 Found :1.2385

Источник

Оцените статью