4

So my question is the following: I get an error on line 12 that I want to solve but haven't found the result for. I use Eclipse to run and write my code.

This is what I do:

  1. I write absolute
  2. I enter a number with decimals
  3. an error pops up saying

    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)
    

How come this does not work? Also, I tried running it in CMD outside of Eclipse aswell, without sucess.

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

3 に答える 3

1

InputMismatchException, this exception thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

num1.nextDouble() -> Here your passing value does not match the double regular expression, or is out of range.

于 2012-11-12T08:13:18.793 に答える
1

Your code is working for me if i put valid input input for your program .

If you are getting InputMismatchException means you are not providing expected input to Scanner.

double numberone1 = num1.nextDouble();

For this from your command you should give Double value only otherwise it will throw InputMismatchException

于 2012-11-12T08:23:07.140 に答える
-1

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"));

    }
}
于 2014-02-21T21:47:56.873 に答える