Hevar
Hevar

Reputation: 1529

simple Java distance calculator.

Whenever I run x1 (or any other int) as a number with a decimal (e.g. 3.7) I get the error message below. I have tried to find out what causes the error but since I'm not a very good Java programmer (yet :) ) I cant seem to figure it out.

Thanks in advance.

The error message:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at MathAvstand.main(MathAvstand.java:12)

The program:

import java.lang.Math;
import java.text.DecimalFormat;
import java.util.Scanner;

public class MathAvstand {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        System.out.print("x1: ");
        double x1 = keyboard.nextInt();

        System.out.print("x2: ");
        double x2 = keyboard.nextInt();

        System.out.print("y1: ");
        double y1 = keyboard.nextInt();

        System.out.print("y2: ");
        double y2 = keyboard.nextInt();

        double a = x1 - x2;
        double b = y1 - y2;

        double summa1 = Math.pow(a,2)+ Math.pow(b,2);

        double avstand = Math.sqrt(summa1); 

        System.out.println("x1: " + x1);
        System.out.println("x1: " + x2);
        System.out.println("x1: " + y1);
        System.out.println("x1: " + y2);
        System.out.println("Avståndet mellan punkterna är: " + avstand); 


    }

}

Upvotes: 0

Views: 274

Answers (4)

CyanogenCX
CyanogenCX

Reputation: 404

Call the method next() instead of nextInt() to fix it. You could also as others have suggested change it to nextDouble(), this is just another suggestion.

Upvotes: 0

MarkHorwell
MarkHorwell

Reputation: 36

The issue is that you are using a nextInt and then entering a double.

Try:

double x1 = keyboard.nextDouble();

Upvotes: 0

Jordando
Jordando

Reputation: 356

You are getting an error called InputMismatchException because

  keyboard.nextInt() 

is looking for an int, but you are passing it a double

try replacing all those with

keyboard.nextDouble();

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

Change the calls from Scanner.nextInt() to Scanner.nextDouble() like

double x1 = keyboard.nextDouble();

an int is not a floating point number.

Upvotes: 1

Related Questions