Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

Accept Integer only in if else statement

package shipcost;

import java.io.*;

//Your class should be ShipCost (All words starting with uppercase)
public class ShipCost {

    public static void main(String[] args) {

    //Declare and initialize your variables first (with invalid values for your program)
    double input = -1;
    double total = 0;
    String s1 = null;

    //This will loop to prompt the user until the input is correct
    while (true) {

        try {
            //try to execute the folowing lines
            s1 = getInput("enter the item price");
            input = Integer.parseInt(s1);

            //If everything went fine, break the loop and move on.
            break;

        } catch (NumberFormatException e) {

            //If the method Integer.parseInt throws the exception, cathc and print the message.
            System.out.println("Not a valid input, please try again.");
        }
    }


    if (input < 100) {

        //What is this line exactly doing?
        //double total = input += input * .02;

        //This is better. If input less than 100, charge 2% over the price.
        total = input * 1.02;

        System.out.println(total);

        //How can you return something from a void method (in this case main).
        //The statement below will not compile
        //return stdin.readLine();

    } else {

        //If greater than or equal to 100, do not charge shiping.
        total = input;
        System.out.println(total);

    }

}

    private static String getInput(String prompt) {

        //Comment your code for your own good, it makes more readable and helps you in future ref.
        BufferedReader stdin = new BufferedReader(
                new InputStreamReader(System.in));

        //Separate your line in chunks for commenting.
        System.out.print(prompt);
        System.out.flush();

        try {
            return stdin.readLine();
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Accept #Integer #statement
ADD COMMENT
Topic
Name
7+9 =