mardi 15 août 2017

How to write an if/else statement to check type of variable

I'm trying to write a program that reads two numbers from the standard input and finds whether they are in the golden ratio and to print an error message if the input is not numeric. But the if/else with "instanceoff" isnt working properly, it comes up as an error if input is not numeric and the says its not a golden ratio even if it is.

Thanks

import java.util.Scanner;

public class GoldenRatio {

        public static void main(String[] args) {
        Scanner key = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
        Double a = key.nextDouble();
        Double b = key.nextDouble();
        Double x;
        Double y;
        
        //Makes sure the bigger number becomes numerator
        if(a <= b){
                x= b;
                y= a;
        } else {
                x = a;
                y = b;
        }
        
        //Rounding decimal to 3 figures
        Double left = (x+y)/x;
        Double right = x/y;
        
        String leftS = String.format("%.3f", left);
        String rightS = String.format("%.3f", right);
        
        Double leftD = Double.parseDouble(leftS);
        Double rightD = Double.parseDouble(rightS);
        
        // meant to make sure arguments are doubles             
        if (a instanceof Double && b instanceof Double) {
                if (leftS == rightS)    {
                        System.out.println("Golden ratio!");
                } else {
                        System.out.println(leftS);
                        System.out.println(rightS);
                        System.out.println("Maybe next time");
                        System.exit(0);
                }
        }else {
                System.out.println("Invalid input");
                System.exit(0);
        }
 }
}

Aucun commentaire:

Enregistrer un commentaire