mardi 30 octobre 2018

Forbidding program from inputting a number less than 1 (if else / switch)

So I'm writing a program that compares box volumes... but I need to make it run so that values less than one are not printed and would prompt an error message. (i.e. "The first box is 0.5 times the size of the second box" or "The first box is 0 times the size of the second box") -- Instead I would like it to print "Error: Please enter a valid number greater than 1"

Here is the part of my code that I am trying to fix:

if (volume1 == volume2) {
        System.out.println("The first box is the same size as the second box");
    }else if(volume1 >= 0 || volume2 >= 0){
        System.out.println("Error. Please enter a valid number greater than 0");
    }else {
        String bigger = "first box";
        String smaller = "second box";
        double ratio = volume1 / volume2;
        if (volume2 > volume1) {
            bigger = "second box";
            smaller = "first box";
            ratio = volume2 / volume1;
        }
        String compare;
        switch((int) ratio) {
        case 1: compare = " is slightly bigger than "; 
        break;
        case 2: compare = " is twice the size of "; 
        break;
        case 3: compare = " is triple the size of ";
        break;
        case 4: compare = " is quadruple the size of "; 
        break;
        default: compare = " is " + (int) ratio + " times the size of ";
        break;
        }

        System.out.println("The " + bigger + compare + smaller);
    }

I hope this is enough code to explain what my issue is. From what I have learned I don't think switch statements can have conditions, and because of the way the int ratio is structured it keeps printing 0 when I test it. Any advice?

Aucun commentaire:

Enregistrer un commentaire