Получение InputMismatchException во время выполнения, но компилирует нормально


import java.util.Scanner;

public class DRYeck {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);                               //declaration scanner

        System.out.println("What is given:");

        System.out.print("How many sides?");                                    //input the number of Sides that are given
        System.out.println("");
        double input = scanner.nextInt();
        System.out.print("How many angles? ");                                  //input the number of Angles that are given 
        System.out.println("");
        double input2 = scanner.nextInt();

        if((input+input2)>3){                                                   //observes if the input is higher than 3 and errors if this is so

            System.out.println("Please enter only 3 entries, you entered "+((int)(input+input2))+" eingegeben...");

        }else if((input==1) && (input2==2)){

            double side1 = inputDialogSide();                                   //input a Side
            double angle1 = inputDialogAngle();                                 //input an Angle
            double angle2 = inputDialogAngle();                                 //input an Angle

            oneSideTwoAnglesGeneral(side1,angle1,angle2);

        }else if((input==2) && (input2==1)){

            System.out.println("Is the angle inclsive or exclusiv?");

            String input3 = scanner.nextLine();                                 //input 3 for identification if the angle is inclusive or exclusive

            if(input3.equals("inklusiv")){                                      //set variable 'inclu' to true if 'inclusive' is entered
                                                                                //distinction of cases into inclusive and exclusive angle

                double side1 =  inputDialogSide();                              //input one Side
                System.out.println("");
                double side2 = inputDialogSide();                               //input the other Side
                System.out.println("");
                double angle1 = inputDialogAngle();                             //input the Angle

                twoSidesOneAngleIncl(side1,side2,angle1);

            }else{

                double side1 =  inputDialogSide();                              //input one Side
                double side2 = inputDialogSide();                               //input the other Side
                double angle1 = inputDialogAngle();                             //input the Angle

                twoSidesOneAngleExcl(side1,side2,angle1);

            }
        }else if((input==3) && (input2==0)){                                                        //condition if 3 Sides are inputed

            double side1 = inputDialogSide();                                   //input first Side
            double side2 = inputDialogSide();                                   //input second Side
            double side3 = inputDialogSide();                                   //input third Side

            threeSides(side1,side2,side3);

        }

    }

    public static double inputDialogAngle(){                                    //subroutine for inputing an Angle
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an angle: ");
        double input5 = scanner.nextDouble();                                   //input5(variable) for an Angle
        System.out.println("");
        return input5;
    }

    public static double inputDialogSide(){                                     //subroutine for inputing a Side
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the sidelength: ");
        double input4 = scanner.nextDouble();                                   //input4(variable) for a Side
        System.out.println("");
        return input4;
    }


    static void collection(double alpha,double beta, double gamma,double sidea,double sideb,double sidec){  //sorting the value in the array

        double[][] SidesAngles = new double [3][2];                             //array for side length value of the angles

        for(int i=0;i<SidesAngles.length;i++){
            for(int j=0;j<SidesAngles[i].length;j++){
                if((SidesAngles[0][0]==0)){
                    SidesAngles[0][0]=sidea;
                }else if((SidesAngles[0][1]==0)){
                    SidesAngles[0][1]=alpha;
                }else if((SidesAngles[1][0]==0)){
                    SidesAngles[1][0]=sideb;
                }else if((SidesAngles[1][1]==0)){
                    SidesAngles[1][1]=beta;
                }else if((SidesAngles[2][0]==0)){
                    SidesAngles[2][0]=sidec;
                }else if((SidesAngles[2][1]==0)){
                    SidesAngles[2][1]=gamma;
                }
            }
        }
        PrintArray(SidesAngles);
    }

    public static double angleDiff(double angle1, double angle2){
        double resuAng = 180-angle1-angle2;
        return resuAng;
    }

    static void PrintArray(double SidesAngles[][]){ //printing the Array with all values
        String[][] AngleSideNames = {{"Seite a","Alpha"},{"Seite b","Beta"},{"Seite c","Gamma"}};   //Names of angles and Sides

        for(int i=0;i<SidesAngles.length;i++){
            for(int j=0;j<SidesAngles[i].length;j++){
                System.out.print(AngleSideNames[i][j]+": "+SidesAngles[i][j]+"n");
            }
        }
    }

    public static double sinusRule(double angle1, double angle2, double side){
        double angle3 = angleDiff(angle1,angle2);                                           
        double resuSide = side*(Math.sin(angle1)/Math.sin(angle2));
        return resuSide;
    }

    static void threeSides(double sidea, double sideb, double sidec){           //subroutine for 3 Sides that are given
        double alpha = Math.acos((Math.pow(sidea, 2)+Math.pow(sideb, 2)-Math.pow(sidec, 2))/(2*sidea*sideb));
        alpha = Math.toDegrees(alpha);                                          //alpha in degree
        double beta = Math.acos((Math.pow(sidea,2)+Math.pow(sidec,2)-Math.pow(sideb,2))/(2*sidea*sidec));
        beta = Math.toDegrees(beta);                                            //output in degree
        double gamma = angleDiff(beta,alpha);                                   //determine the angle differance
        collection(alpha,beta,gamma,sidea,sideb,sidec);

    }

    static void twoSidesOneAngleIncl(double sidea, double sideb, double gamma){ //subroutine for 1 Angle(inclusive) and 2 Sides
        double sidec = Math.sqrt(Math.pow(sidea,2)+Math.pow(sideb,2)-(2*sidea*sideb*Math.cos(gamma)));
        double alpha = Math.acos((Math.pow(sideb,2)+Math.pow(sidec, 2)-Math.pow(sidea, 2))/(2*sideb*sidec));
        double beta = angleDiff(alpha,gamma);
        collection(alpha,beta,gamma,sidea,sideb,sidec);
    }

    static void twoSidesOneAngleExcl(double sideb, double sidec, double beta){  //subroutine for 1 Angle(exclusive) and 2 Sides 

        double sidea=0,alpha=0,gamma=0;                                         //initialize sidea, alpha, gamma
        double d = ((sidec/sideb)*Math.sin(beta));                              //variable for further movement
        boolean acute=false,obtuse=false;                                       //initialize check-variable for acute or obtuse triangle

        if(d>1){                                                                //condition if check-variable is higher than 1
            System.out.println("There is no solution for this triangle");
        }else if(d==1){                                                         //if check-variable equals 1
            gamma = 90;                                                         //gamma=90° because of the conditions
            sidea = Math.sqrt(Math.pow(sideb,2)+Math.pow(sidec,2));             //solve sidea with pythagorean theorem
        }else{                                                                  //if check-variable is lower than 
            System.out.print("Is the traingle obtuse or actuse: ");
            Scanner scanner = new Scanner(System.in);                           //input for acute or obtuse statement
            String input = scanner.nextLine();

            if(input.equals("obtuse")){                                         //sets the right boolean to true so further operations are correct
                acute = true;
            }else if(input.equals("acute")){
                obtuse = true;
            }

            if((sideb<sidec) && (acute)){                                       //checks if b<c and the triangle should be acute
                gamma = Math.asin(d);
                System.out.println("angle gamma: "+gamma);

                sidea = sinusRule(beta,gamma,sideb);                            //Side a

            }else if((sideb<sidec) && (obtuse)){                                //checks if b<c and the triangle should be obtuse
                gamma = Math.asin(d);
                gamma = 180-gamma;
                System.out.println("angle gamma: "+gamma);

                sidea = sinusRule(beta,gamma,sideb);                            //Side a

            }
            System.out.println("There is no solution!!!");
        }
        collection(alpha,beta,gamma,sidea,sideb,sidec);
    }

    static void oneSideTwoAnglesGeneral(double sidec, double alpha, double beta){//subroutine for one side and two angles that are given
        double gamma = angleDiff(alpha,beta);                                   //determine the third angle
        double sidea = sidec*(Math.sin(alpha)/Math.sin(gamma));                 //determine side with the law of sinus
        sinusRule(alpha,gamma,sidec);
        double sideb = sidec*(Math.sin(beta)/Math.sin(gamma));                  //same here to determine side b
        sinusRule(beta,gamma,sidec);

        collection(alpha,beta,gamma,sidea,sideb,sidec);
    }
}

Исключение:

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 DRYeck.inputDialogSide(DRYeck.java:85)
   at DRYeck.main(DRYeck.java:52)`
Мой вопрос теперь в том, как избавиться от исключения. Эта программа предназначена для вычисления всех сторон и углов треугольника только с 3 входами. Например, один угол и 2 стороны или 2 угла и 1 сторона и так далее.
2 2

2 ответа:

Ваша проблема связана с этим разделом кода:

else if((input==2) && (input2==1)){

            System.out.println("Is the angle inklsiv or exclusiv?");

            String input3 = scanner.nextLine();                                 //input 3 for identification if the angle is inclusive or exclusive

            if(input3.equals("inklusiv")){ 

Поскольку вы запрашиваете здесь не полную строку, а только маркер, используйте сканер.next() вместо Scanner.nextLine ();

Публичная строка next () Находит и возвращает следующий полный маркер из этого сканера. Полный маркер предваряется и сопровождается вводом, который соответствует шаблону разделителя. Этот метод может быть заблокирован во время ожидания ввода для сканирования, даже если предыдущий вызов hasNext () возвращен истинный.

Поэтому измените эту строку:

 String input3 = scanner.nextLine();

К

 String input3 = scanner.next();

И ваша программа должна работать нормально!

Я думаю, что здесь есть проблема:

double input = scanner.nextInt();

Измените его на этот и все другие случаи:

double input = scanner.nextDouble();