Getting I / O of Decimal Numbers for Math.abs

So, my question is the following: I get an error message on line 12, which I want to solve, but did not find the result for. I use Eclipse to run and write my code.

This is what I do:

  • I write absolute
  • I enter a decimal number
  • error message appears

    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.nextDouble(Unknown Source) at apples.main(apples.java:12) 

Why is this not working? In addition, I tried to run it in CMD outside of Eclipse, but without success.

 import java.util.Scanner; class apples { public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Select one of the following(absolute,ceil,floor,max,min,power,squareroot): "); String code = scan.nextLine(); if (code.contains("absolute")) { System.out.println("Enter a number to get absolute value: "); Scanner num1 = new Scanner(System.in); double numberone; double numberone1 = num1.nextDouble(); System.out.println(Math.abs(numberone1)); } } } 
+4
source share
3 answers

Your code works for me if I put valid input for your program.

If you get an InputMismatchException , then you are not providing the expected input for the scanner.

 double numberone1 = num1.nextDouble(); 

For this, from your command you must give a double value only otherwise it will throw an InputMismatchException

+1
source

An InputMismatchException is an exception thrown by the scanner to indicate that the received token does not match the pattern for the expected type or that the token is out of range.

num1.nextDouble() → Here, your transfer value does not match a double regular expression or is out of range.

+1
source

import java.util.Scanner;

 public class Test{ private static Scanner scan; private static Scanner num1; public static void main(String[] args){ scan = new Scanner(System.in); String code; do{ System.out.println("Select one of the following(absolute,ceil,floor,max,min,power,squareroot): "); code = scan.nextLine(); if (code.contains("absolute")) { System.out.println("Enter a number to get absolute value: "); num1 = new Scanner(System.in); //double numberone; double numberone1 = num1.nextDouble(); System.out.println(Math.abs(numberone1)); } }while(!code.contains("absolute")); } } 
-1
source

Source: https://habr.com/ru/post/1445456/


All Articles